How to use the .NET Timer class to trigger an event at a specific time?

前端 未结 9 1684

I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and

9条回答
  •  旧巷少年郎
    2020-12-01 00:38

    Starting with .NET 4.5 there's a really clean solution:

    public async void ScheduleAction(Action action, DateTime ExecutionTime)
    {
        await Task.Delay((int)ExecutionTime.Subtract(DateTime.Now).TotalMilliseconds);
        action();
    }
    

    Here's a solution without async/await:

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

    It should be noted that this only works for about 24 days out because of int32 max value, which is plenty for your case, but worth noting.

提交回复
热议问题