Search code examples
c#timerwindows-servicesautoresetevent

Can my use of System.Threading.Timer be more efficient


I´m looking for some advice about making my code more efficient. What I would like to do is to have a System.Threading.Timer that runs some job every hour or so, the job is not going to be very heavy but I would like to have a code that does not take much of resources. I plan to run this code in a windows service.

This is what I have so far.

class Program
{
    private static Timer timer;

    static void Main(string[] args)
    {
        SetTimer();
    }

    static void SetTimer()
    {
        timer = new Timer(Write);

        var next = DateTime.Now.AddHours(1);

        var nextSync = (int)(next - DateTime.Now).TotalMilliseconds;

        timer.Change(nextSync, Timeout.Infinite);
    }

    static void Write(object data)
    {
        Console.WriteLine("foo");

        SetTimer(); //Call the SetTimer again for the next run.
    }
}

What do you guys think? Can I make my code more efficient?

All advice is much appreciated!


Solution

  • Several points:

    • You do not have to create a new timer every hour.
    • Setting the second parameter to infinite, makes you have to reload the timer manually. But... In this case, why should you?
    • You make a difficult calculation to create a timespan from one hours form now: now + 1 hour - now. This can solved easily.

    Try this:

    class Program
    {
        private static Timer timer = new Timer(Write, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
    
        static void Main(string[] args)
        {
        }
    
        static void Write(object data)
        {
            Console.WriteLine("foo");
        }
    }