I'm writing a hosted service in .Net-Core which runs a job in the background based off of a timer.
Currently I have to code running synchronously like so:
public override Task StartAsync(CancellationToken cancellationToken)
{
this._logger.LogInformation("Timed Background Service is starting.");
this._timer = new Timer(ExecuteTask, null, TimeSpan.Zero,
TimeSpan.FromSeconds(30));
return Task.CompletedTask;
}
private void ExecuteTask(object state)
{
this._logger.LogInformation("Timed Background Service is working.");
using (var scope = _serviceProvider.CreateScope())
{
var coinbaseService = scope.ServiceProvider.GetRequiredService<CoinbaseService>();
coinbaseService.FinalizeMeeting();
}
}
I'd like to run this Async on the timer but I don't want to run async using fire and forget because my it could cause race conditions in my code.
e.g( subscribing to the timer.Elapsed
event)
Is there a way I can leverage asynchronous code on a timed schedule without executing fire and forget
private async Task ExecuteTask(object state)
? – Cuevas