Does System.Threading.Timer rely on system time being correct?
I have a service which runs a job every 30 minutes based on a System.Threading.Timer. The timer is setup with an interval as usual and fires the job off asynchronously.
Last night the time on the server it resides on decided to reset itself to something completely different to the actual time & date. Subsequently, my jobs did not run every 30 minutes - infact they completely stopped.
However, upon resetting the time this morning the next 30 minute task ran itself (30 minutes later) and then ALL of the other tasks ran themselves at the same time as if they had been queuing开发者_如何学C all night.
Can anyone shed any light on this?
EDIT: As an update - using the other timer (System.Timers.Timer) and exactly the same thing happened. Time changes to something completely different, service then stops completing its tasks until the time is subequently reset in the morning and then 30mins later it runs ALL of the tasks which should have run every 30 mins since the time changed!
I can't replicate a scenario that results in this.
Using this code
class Program
{
private static Timer timer;
private static readonly Stopwatch stopwatch = new Stopwatch();
static void Main(string[] args)
{
timer = new Timer(Tick);
stopwatch.Start();
timer.Change(30000, Timeout.Infinite);
Console.ReadLine();
}
private static void Tick(object obj)
{
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.Seconds);
}
}
I start the app, change my local computer time to 20 seconds in the future. The Tick method is still called 30 seconds after I started the app. The stopwatch says 30 and my mobilephone timer says 30.
I think that's because the Timer queues callbacks for execution by thread pool threads and maybe it schedules the callback for an actual time in the future and not an interval.
@GertArnold's answer is correct you should use System.Timers.Timer instead because it raises the Elapsed event, based on the value of the Interval property.
Since you tried all relevant built-in options regarding timers only the following options are left:
use
Sleep
- this is something I see as bad practice BUT in your specific case should solve the problem desribedfind some 3rd-party timer library and test it with your rather special cicumstances...
精彩评论