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.
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:
.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With