Search code examples
c#multithreadingtimer

How to set timer to execute at specific time in c#


I have a requirement where i need to execute timer at 00:01:00 A.M every day...But i am not getting how to achieve this ..If i am taking Systems time,it can be in different format.. Here is my timer code..

static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer(); 

static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add timer code here

    }
    private static void start_timer()
    {
        timer.Start();
    }

Solution

  • What you should do is write your program that does whatever you need it to do, and then use your OS's built-in task scheduler to fire it off. That'd be the most reliable. Windows's Task Scheduler, for instance, can start your app before the user logs in, handle restarting the app if necessary, log errors and send notifications, etc.

    Otherwise, you'll have to run your app 24/7, and have it poll for the time at regular intervals.

    For instance, you could change the interval every minute:

    timer.Interval = 1000 * 60;
    

    And inside your Elapsed event, check the current time:

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (DateTime.Now.Hour == 1 && DateTime.Now.Minute == 0)
        {
            // do whatever
        }
    }
    

    But this is really unreliable. Your app may crash. And dealing with DateTime's can be tricky.