Background service

in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddHostedService<backgroundService>();
}

in helper class

namespace projectnaam.helper
{
    public interface IScoped { }

    public class Scoped : IScoped { }
    public class backgroundService : BackgroundService
    {

        public backgroundService (...)
        {
            ...
        }
        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                        // VOER CODE UIT
                    }
                    
                }
                await Task.Delay(10000, stoppingToken);
            }
            
        }
    }
}

 

Categories: ,

Related Article