我有一个将在 asp.net 应用程序中调用的类库。现在我想间隔运行一个函数来从数据库中获取数据。我想使用静态构造函数来触发间隔函数。这个想法可行吗?
以下是我要实现上述想法的代码草案。
//This is one class that stays in the class library assembly.
public class UsageManager : IUsageManager
{
static UsageManager()
{
//when the first time this class is called, it will run the function, and it will keep running non-stop to refresh the data periodically.
RefreshData();
}
}
public void RefreshData()
{
try
{
this.timerObj = new Timer(LoadData, null, Timeout.Infinite, Timeout.Infinite);
this.timerObj.Change(0, Timeout.Infinite);
}
catch (Exception ex)
{
//Log error
}
}
private void LoadData(object state)
{
try
{
TimeSpan elapsed = DateTime.Now - this.lastUpdateTS;
if (elapsed.TotalMinutes >= this.refreshInterval)
{
// Load value from database
ProcessRecord();
this.lastUpdateTS = DateTime.Now;
}
// 6 seconds interval to call the method again..
this.timerObj.Change(6000, Timeout.Infinite);
}
catch (Exception ex)
{
// log exception
}
}