Scheduling Task for future execution

2019-06-19 08:10发布

问题:

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 Tasks. Task has .Delay(...) methods, but not sure delay is similar to scheduling.

Edit(clarification): I want to start tasks after x minutes.

回答1:

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.



回答2:

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;