I have a BackgroundService called Worker, which I override the ExecuteAsync method to run something each 10 seconds. Sometimes, what I run lasts very long. In this scenario, I want to kill what I am running, then rerun it. How can I achieve this?
My BackgroundService is as follows:
public class Worker : BackgroundService {
private readonly ITask task;
private readonly IHostApplicationLifetime appLifeTime;
public Worker(ITask task, IHostApplicationLifetime appLifeTime) {
this.task = task;
this.appLifeTime = appLifeTime;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested)
{
try {
this.task.Execute(stoppingToken);
} catch (Exception e) {
this.appLifeTime.StopApplication();
}
await Task.Delay(10000, stoppingToken);
}
}
}
public interface ITask {
void Execute(CancellationToken stoppingToken);
}