我使用的计时器在Windows上的OnStart()方法处理timer_Elapsed()事件检查后,每5分钟。
但是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);
}
}发布于 2016-06-09 11:10:12
我想这可能是因为你是在用的块里做的。
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();发布于 2016-06-09 11:13:20
https://stackoverflow.com/questions/37724094
复制相似问题