Reputation:
I have a program written in C#. I want the Timer class to run a function at a specific time.
E.g : run function X at 20:00 PM
How can I do that using the Timer class?
Upvotes: 3
Views: 1139
Reputation: 18810
Use the Timer Tick event to check (Set the tick to a suitable value) then in the tick event:
DateTime Now = DateTime.Now;
if(Now.Hours == DateTimeCallX.Hours
&& Now.Minutes == DateTimeCallX.Minutes
&& xHasRan == false)
{
x();
xHasRan = true;
}
DateTimeCallX being a DateTime object set to 20:00.
xHasRan is a boolean stating whether the function has been called, this will be initially set to false and set to true after x has been called so that if the timer tick runs again in the same minute then it won't run the function again.
Upvotes: 2
Reputation: 9020
You would have to calculate the number of milliseconds until 20:00 PM or use a scheduler like Quartz.NET.
Upvotes: 0
Reputation: 146557
Set the timer to run a method that checks what time it is, and run your code if the desired time has past, or goes back to sleep for FEW MILLISECONDS IF IT HAS NOT.
Upvotes: -1
Reputation: 17129
When the timer fires, check the time and whether the function has run that day. If the time is after 20:00 and the function hasn't been called, call it. Otherwise, exit and wait for the next event.
Also, keep in mind that the forms timer and System.Threading.Timer work slightly differently.
Upvotes: 2