稍后执行功能

时间:2016-02-17 23:22:49

标签: c# scheduled-tasks

我有以下代码,其目的是在特定时间调用函数。但是,当WaitTask.Start();被调用Additional information: Start may not be called on a promise-style task.

时,我会收到异常
DateTime today = DateTime.Today;
DateTime twoThirtyET = today.AddHours(14.50);

Execute(CallAtTime, twoThirtyET);

public void Execute(Action action, DateTime ExecutionTime)
{
    Task WaitTask =          Task.Delay((int)ExecutionTime.Subtract(DateTime.Now).TotalMilliseconds);
    WaitTask.ContinueWith(_ => action);
    WaitTask.Start();
}

private void CallAtTime()
{
    Console.WriteLine("Called at time");
}

3 个答案:

答案 0 :(得分:2)

由于Additional information: Start may not be called on a promise-style task.中的Task已经启动,您收到Task.Delay,请查看this answer以获取更多信息。

最简单的更改是删除对WaitTask.StartNew()的调用,因为这是不必要的。

哦,您可能希望在回调中实际调用您的操作,而不是仅仅返回它:

WaitTask.ContinueWith(_ => action());

答案 1 :(得分:1)

您可以使用计时器。 (2000是以毫秒为单位的间隔,所以2秒)

class Program
{
    private static System.Timers.Timer _timer;
    static void Main(string[] args)
    {
        _timer = new System.Timers.Timer(2000);
        _timer.Elapsed += timer_Elapsed;
        _timer.Start();
        Console.ReadLine();
    }

    static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        _timer.Stop(); //If you only want it to run once
        Console.WriteLine("Elapsed");
    }
}

答案 2 :(得分:-1)

完整示例

namespace YourNamespace
{
    using System.Threading;

    public class MainClass
    {
        public void Main()
        {
            PostponedAction action = new PostponedAction();
            action.WaitExecute(DateTime.Today.AddHours(14.5) - DateTime.Now);
        }
    }

    public class PostponedAction
    {
        public void WaitExecute(TimeSpan waitTime)
        {
            Thread.Sleep(waitTime);
            // Do stuff
        }
    }
}