我用于执行自动化任务的服务存在问题。
该服务使用计时器并在 20 秒后执行。
执行的函数打开数据库,从中读取数据,通过网络发送值,接收响应并使用该响应更新数据库。
它一直运行良好,直到我想要对数据库中大约 1000 行执行自动化任务,系统“失败”了。检查日志后,我发现即使前一个实例仍在执行,该函数也会在间隔后执行。该函数应该发送一条消息,一些客户抱怨没有收到消息,而另一些客户却收到了多达六次。
是否有任何简单有效的方法来确保如果先前的实例仍在运行,该函数将不会运行。
如果我在函数中启动和停止时间,它只会将“通过”的时间添加到间隔中
这是代码
public partial class Service1 : ServiceBase
{
private Timer timer1 = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 20000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled = true;
Library.WriteErrorLog("service has started");
}
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
try
{
//retrieve data from database
//read rows
//Loop through rows
//send values through network
//receive response and update db
}
catch (Exception ex)
{
Library.WriteErrorLog(ex);
}
}
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("service has stopped");
}
}
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
Timer timer = sender as Timer;
timer.Enabled = false; // stop timer
try
{
//retrieve data from database
//read rows
//Loop through rows
//send values through network
//receive response and update db
}
catch (Exception ex)
{
Library.WriteErrorLog(ex);
}
finally
{
timer.Enabled = true; // start timer again, no overlapping
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)