I have looked at the Task and Timer class API's, but could not find information on how to schedule a Task
for future execution.
Using the Timer
class, I can schedule threads for future execution, but I need to schedule Task
s.
Task
has .Delay(...)
methods, but not sure delay is similar to scheduling.
Edit(clarification): I want to start tasks after x minutes.
You should use Task.Delay
(which internally is implemented using a System.Threading.Timer
):
async Task Foo()
{
await Task.Delay(TimeSpan.FromMinutes(30));
// Do something
}
While the delay is "executed" there is no thread being used. When the wait ends the work after it would be scheduled for execution.
I would use this Timer (System.Timers.Timer) instead. It's a bit simpler to use. Set the interval to 30 and start the timer, making sure the elapsed event calls the method you want to happen. You can stop it afterwards if you only want it to happen once and not every thirty minutes.
Code sample from the linked MSDN page:
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;