Reputation: 745
I want to raise an event every time each hour has passed in system clock. For example, I run my program at 7:45 am then the event should be raised at 8:00 am, not at 8:45 am. After the event raised at 8:00 am, then this event should be raised at every hour 9:00 am, 10:00 am, 11:00 am, etc...
Can anyone help me to show some code... I use C#.net... Thanks in advance...
UPDATE:
Now I get the simple solution for my question. Therefore I would like to share this solution. lboshuizen's answer is already correct. My answer is same logic with lboshuizen's answer but more detail and exact.
Firstly it needs to use Timer. Timer basically works based on milliseconds which sometimes needs additional calculation. Therefore, I would like to implement milliseconds to minute formatting function as first.
int CalculateMillisecondUntilNextHour()
{
int REMAIN_MINUTE = 60 - DateTime.Now.Minute;
DateTime now = DateTime.Now;
DateTime nexthour = now.AddMinutes((minute)).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
TimeSpan interval = nexthour - now;
return (int)interval.TotalMilliseconds;
}
void CheckEachHourPassed()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = CalculateMillisecondUntilNextHour();
t.Tick += new EventHandler(t_Tick);
t.Enabled = true;
}
void t_Tick(object sender, EventArgs e)
{
MessageBox.Show("Raise Your Event");
t.Interval = CalculateTimerInterval(REMAIN_MINUTE);
}
At here, the main working function is CheckEachHourPassed(). Call this function where you want to start your event scheduler.
Upvotes: 0
Views: 2730
Reputation: 382
The problem is that the
timer.Every().Minutes(60).Execute(() => Code());
over time may actually get out of sync with the real time.
How about running this in a thread
var lastMoment = DateTime.Now;
while(true)
if(DateTime.Now.Hour != lastMoment.Hour)
{
//Raise ElaspedHourEvent
//Thread.Sleep(1000);
]
it might not fire the event until at most a second after the hour but at least it won't get out of sync.
Upvotes: 0
Reputation: 2786
Pseudo code (implementation is left as an excercise to the reader)
var currentTime = Time.Now()
var deltaMinutes = Calculate_minutes_till_next_full_hour(currentTime);
wait(deltaMinutes);
var timer = new timer();
timer.Every().Minutes(60).Execute(() => Code());
Upvotes: 1
Reputation: 28980
You can use Timer
by fixing Interval
property
Link : http://msdn.microsoft.com/fr-fr/library/system.timers.timer.aspx
Upvotes: 0