Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does System.Threading.Timer rely on system time being correct?

Tags:

c#

.net

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 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!

like image 886
Daniel Frear Avatar asked Sep 23 '11 08:09

Daniel Frear


1 Answers

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.

like image 120
Paw Baltzersen Avatar answered Nov 16 '22 22:11

Paw Baltzersen