Reputation: 1899
This is a rather simple issue, but every time I try to find the answer it keeps showing things about Windows Scheduled Tasks, and this is not what this is.
Say my program is basically this:
void StartDoingThings()
{
//At Specific System.DateTime
DoSomething()
//At another specific System.Datetime
DoSomethingElse()
}
What do I put instead of those comments to cause those methods to run at separate datetimes.
I could use Thread.Sleep() or even System.Threading.Timers and calculate intervals based off of (DateTimeOfEvent - DateTime.Now), but is there simply something to say (assuming the program is still running): At 9:30:00 AM on 11/30/2012, perform the method DoAnotherThing() ?
Upvotes: 6
Views: 5322
Reputation: 34810
If you want to "schedule" a method to do something at a predetermined time, there are a number of ways to do that. I would not use Thread.Sleep()
because that would tie up a thread doing nothing, which is a waste of resources.
A common practice is to use a polling method that wakes up on a regularly timed schedule (let's say once a minute) and review a shared list of tasks to perform. System.Timer
can be used for the polling method:
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
The OnTimedEvent method can contain code that maintains a collection of "tasks" to perform. When a task's time comes up, the next run of the Timer will cause it to execute.
Upvotes: 4