0

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

示例:在 2020 年 5 月 19 日上午 6 点开始比赛,有一次我使用以下方法此方法延迟两秒:

 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,"");
            }
        }
4

1 回答 1

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();
    }

如果需要返回值,请用and替换Taskand 。ActionTask<T>Func<T>

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

于 2020-05-19T14:59:29.400 回答