Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly fire tick event on completion of hour in C# Timer

Tags:

c#

events

timer

I want the tick event to fire every hour exactly on completion of the hour. For e.g. it should tick on 8 am then on 9 am then on 10 am etc. It's simple that I need to set the Interval to 3600000.

The problem here is how should I identify when should I start the timer? I'm creating a tool which will run in system tray from the time when user will log on.

like image 376
IsmailS Avatar asked Dec 06 '22 00:12

IsmailS


2 Answers

Please don't create a program that does nothing but waste memory. That's what Windows' Task Scheduler is for. Run your program every hour from such a task.

http://msdn.microsoft.com/en-us/library/aa384006%28v=VS.85%29.aspx

Here's a sample:

  • Go to Start->Programs->Accessories->Scheduled Tasks.
  • On the right side, click "Add Task..".
  • Select your executable.
  • Go to the Trigger tab.
  • Create Trigger with the following selection:

.

Run Daily 
Start today at 8:00 am
Repeat every 1 Hour

I'm sorry that I can't provide any screenshots since I'm running the german version of Windows 7.

like image 136
VVS Avatar answered Dec 07 '22 15:12

VVS


May be bellow code is buggy, but the idea is this:

    public void InitTimer()
    {
        DateTime time = DateTime.Now;
        int second = time.Second;
        int minute = time.Minute;
        if (second != 0)
        {
            minute = minute > 0 ? minute-- : 59;
        }

        if (minute == 0 && second == 0)
        {
            // DoAction: in this function also set your timer interval to 3600000
        }
        else
        {
            TimeSpan span = new TimeSpan(0, 60 - minute, 60 - second);
            timer.Interval = (int) span.TotalMilliseconds - 100; 
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
    }

    void timer_Tick(object sender, EventArgs e)
    {
        timer.Interval = 3600000;
        // DoAction
    }

Edit: as @smirkingman offered, I removed some millisecond because of latency of project start-up and running of this application: timer.Interval = (int) span.TotalMilliseconds - 100;

like image 22
Saeed Amiri Avatar answered Dec 07 '22 15:12

Saeed Amiri