我遇到了用于执行自动化任务的服务的问题。 该服务使用Timer并在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");
}
}
答案 0 :(得分:1)
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
}
}
答案 1 :(得分:1)
您正在使用多线程System.Timers.Timer,它在每个Elapsed事件的ThreadPool上调用新线程上的timer1_Tick回调。使用变量来同步执行。
public partial class Service1 : ServiceBase
{
private Timer timer1 = null;
private long isTaskRunning = 0;
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
{
if (Interlocked.CompareExchange(ref isTaskRunning, 1, 0)==1)
{
return;
}
//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
{
Interlocked.Exchange(ref isTaskRunning, 0);
}
}
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("service has stopped");
}
}