同步定时器,以防止重叠 [英] Synchronizing a timer to prevent overlap
问题描述
我正在写运行在间隔变长的活动(一个数据库扫描和更新)Windows服务。我需要这个任务频繁运行,但处理的代码是不是安全的同时运行多个倍。
I'm writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn't safe to run multiple times concurrently.
我怎样才能最简单地设置一个计时器来运行任务每30秒时,切勿重复执行? (我假设 System.Threading.Timer
是适合这个工作的正确的计时器,但可能是错误的)。
How can I most simply set up a timer to run the task every 30 seconds while never overlapping executions? (I'm assuming System.Threading.Timer
is the correct timer for this job, but could be mistaken).
推荐答案
您可以用一个定时器做,但你需要有某种形式的锁定在你的数据库的扫描和更新。一个简单的锁定
同步可能足以防止多个运行的发生。
You could do it with a Timer, but you would need to have some form of locking on your database scan and update. A simple lock
to synchronize may be enough to prevent multiple runs from occurring.
话虽这么说,这可能是更好地之后你操作完成启动一个定时器,并且只使用它一次,然后停止。你的下一个操作之后重新启动它。这会给你的事件间隔为30秒(或N秒),根本没有机会重叠,并没有锁定
That being said, it might be better to start a timer AFTER you're operation is complete, and just use it one time, then stop it. Restart it after your next operation. This would give you 30 seconds (or N seconds) between events, with no chance of overlaps, and no locking.
例如:
System.Threading.Timer timer = null;
timer = new System.Threading.Timer((g) =>
{
Console.WriteLine(1); //do whatever
timer.Change(5000, Timeout.Infinite);
}, null, 0, Timeout.Infinite);
的工作立即.....完成...等待5秒....立即开展工作.....完成...等待5秒.... 的
这篇关于同步定时器,以防止重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!