同步定时器,以防止重叠

编程入门 行业动态 更新时间:2024-10-28 16:23:49
本文介绍了同步定时器,以防止重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在写运行在间隔变长的活动(一个数据库扫描和更新)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秒.... 的

更多推荐

同步定时器,以防止重叠

本文发布于:2023-10-26 21:36:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定时器   以防止

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!