Scheduling Task for future execution

2019-06-19 07:51发布

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.

2条回答
SAY GOODBYE
2楼-- · 2019-06-19 08:23

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;
查看更多
该账号已被封号
3楼-- · 2019-06-19 08:33

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.

查看更多
登录 后发表回答