Reputation: 57
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,"");
}
}
Upvotes: 0
Views: 856
Reputation: 36341
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.
Upvotes: 4