Scheduling Task for future execution

☆樱花仙子☆ 提交于 2019-12-12 10:55:23

问题


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;


来源:https://stackoverflow.com/questions/26656236/scheduling-task-for-future-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!