first you need add class Background Worker and inheritance class "BackgroundService" in namespace "Microsoft.Extensions.Hosting" like this :
public class SalaryCalculateBackgroundWorker : BackgroundService
{
}
services.AddHostedService<SalaryCalculateBackgroundWorker>();
when you inherited class SalaryCalculateBackgroundWorker from "BackgroundService" you should override 3 method like this
public override Task StartAsync(CancellationToken cancellationToken)
{
return base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await DoWork(stoppingToken);
}
catch (Exception exception)
{
//exception
}
}
#region [ Private ]
private async Task DoWork(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await _salaryCalculateService.SalaryCalculateAsync();
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
#endregion [ Private ]