简体   繁体   中英

Schedule task on specific time

which is the best way to start method on specific time (hour and min and sec ) on .net core worker

example: start competition on 19/05/2020 6.00 AM for one time i use below approach this approach delay two seconds:

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

How about something like this:

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

Replace the Task and Action with Task<T> and Func<T> if you want a return value.

Replace Action with Func<Task> (or Func<Task<T>> ) if you want to call an async method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM