[英]timer_Elapsed() Event not firing
我在Windows Service的OnStart()
方法上使用Timer,每隔5分鍾處理timer_Elapsed()
事件檢查。
但是timer_Elapsed()
在5分鍾后未觸發/調用,如果我在下面的代碼中做錯了什么,請糾正我。
protected override void OnStart(string[] args)
{
try
{
genLogs.WriteErrorLog("Service Started OnStart.");
//int tmStart = Convert.ToInt32(ConfigurationManager.AppSettings["tim"]);
using (Timer timer = new Timer(30000)) // (1000 * 5 * 60) for 5 minutes
{
timer.Elapsed += timer_Elapsed;
timer.Start();
//Console.WriteLine("Timer is started");
genLogs.WriteErrorLog("Timer is started.");
//Console.ReadLine();
}
}
catch (Exception ex)
{
genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
genLogs.WriteErrorLog("Service Started Checking Windows Services and Web AppPools.");
serviceLogic.InsertStatus();
genLogs.WriteErrorLog("Service Calls Send SendEmails Method.");
serviceLogic.SendInfo();
}
catch (Exception ex)
{
genLogs.WriteErrorLog("OnStart Service Error: " + ex.Message);
}
}
我認為這可能是因為您正在using塊中執行此操作。
using (Timer timer = new Timer(30000)) // (1000 * 5 * 60) for 5 minutes
{
timer.Elapsed += timer_Elapsed;
timer.Start();
//Console.WriteLine("Timer is started");
genLogs.WriteErrorLog("Timer is started.");
//Console.ReadLine();
} <- Your timer stops existing here
在using塊中執行此操作與說timer.Dispose();相同。 它布置了計時器,因此無法調用任何方法。 這應該工作:
Timer timer = new Timer(30000)
timer.Elapsed += timer_Elapsed;
timer.Start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.