在特定时间安排任务

时间:2020-05-19 14:53:40

标签: c# asp.net-core timer task timing

这是在.net core worker上的特定时间(小时,分钟和秒)启动方法的最佳方法

示例:我在19​​/05/2020上午6.00开始比赛一次,我使用以下方法,这种方法会延迟两秒钟:

 protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await CheckCompetitionStarted();
                await Task.Delay(5, stoppingToken);
            }
        }

 private async Task CheckCompetitionStarted()
        {
            try
            {
                var CurrentComp = _game.GetCurrentCompetition();

                if (CurrentComp != null)
                {
                    if (CurrentComp.PlandStartingTime.Date == DateTime.UtcNow.Date
                        && CurrentComp.PlandStartingTime.Hour == DateTime.UtcNow.Hour
                        && CurrentComp.PlandStartingTime.Minute == DateTime.UtcNow.Minute)
                    {
                        _logger.LogInformation($"Start Competition :{DateTime.Now} ");

                      await  CurrentComp.Start();

                        CurrentComp.Close();
                    }
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex,"");
            }
        }

1 个答案:

答案 0 :(得分:3)

这样的事情如何:

    public async Task RunAtTime(DateTime targetTime, Action action)
    {
        var remaining = targetTime - DateTime.Now ;
        if (remaining < TimeSpan.Zero)
        {
            throw new ArgumentException();
        }

        await Task.Delay(remaining);
        action();
    }

如果要返回值,请用TaskAction替换Task<T>Func<T>

如果要调用异步方法,请用Action(或Func<Task>)替换Func<Task<T>>