计时器如何在.net Windows服务中运行?

时间:2017-08-16 22:51:53

标签: c#

我创建了.net Windows服务,并安排它每5分钟运行一次。 此Windows服务包含发送电子邮件的代码,并在发送电子邮件后更新表。

首先,我发送所有电子邮件,然后将数据库中的所有记录更新为批量。所以我的问题是我将间隔设置为5分钟,是否会破坏我的情况,就像发送电子邮件需要5分钟一样,然后计时器停止而没有更新数据库,或者它继续执行直到它完全执行任务。

_timer = new Timer(5* 60 * 1000);   
 _timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
_timer.AutoReset = true;
 _timer.Start();

........................

{//send one email at a time ..this is in loop
Library.SendEmail(edtls);   

ds.Tables["EDts"].Rows[i]["Sent"] = 1;
ds.Tables["EDts"].Rows[i]["Status"] = "Sent";   
ds.Tables["EDts"].Rows[i].EndEdit();
}..how about timer stop execution here(it sends the emails but doesn't update the table)
ds.Update(EDts, "EmailDts");//updating table here

1 个答案:

答案 0 :(得分:-1)

是的,如果发送电子邮件或数据库更新需要的时间比定时器事件触发的时间长,这可能会很棘手。您可以在两者之间停止计时器并在之后继续计时。

_timer.Stop();
{//send one email at a time ..this is in loop
Library.SendEmail(edtls);   

ds.Tables["EDts"].Rows[i]["Sent"] = 1;
ds.Tables["EDts"].Rows[i]["Status"] = "Sent";   
ds.Tables["EDts"].Rows[i].EndEdit();
}..how about timer stop execution here(it sends the emails but doesn't update the table)
ds.Update(EDts, "EmailDts");//updating table here
_timer.Start();