开发者

Creating Timer Class with Duration and Interval Triggers in C#

Is there a class that allows you to setup an object the will remain active开发者_运维问答 for X seconds (or milliseconds) and optionally allow you to trigger something at an interval of Y seconds (or milliseconds)?

I know there is the System.Timers.Timer but that seems to be for intervals only (and there for not making that interval optional). I am currently building this functionality my self with everything working except for the interval stuff. With extremely long durations or extremely small intervals, the intervals sometimes execute 1 or 2 times less than they should which I know is because there are a few ticks that are being lost each interval execution so the more executing intervals, the more ticks that are lost.

I just want to make sure that nothing currently exists in the .NET 3.5 framework with this exact functionality before I try experimenting with a few ideas to get the intervals always executing the correct amount of times.


The best thing to do is to check the time in the ElapsedEventArgs of your OnTimedEvent(object source, ElapsedEventArgs e) event handler and calculate the difference between when you started it and the fired time (or the last fire time). You can then factor into your logic the exact time interval that the timer fired. I don't think you can ever get the timer to be 100% exact to the milisecond, but you can allow for it if you really require precise timing.


What about the System.Threading.Timer class? You can use Timeout.Infinite, if you don't need to trigger the timer using an interval.


You might want to give Quartz.NET a try. It has a rich API for scheduling any kind of jobs/event with whatever intervals, repetitions and misfires you might require.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜