In ASP.NET Core you can run background tasks by creating a hosted service. You can read the full documentation here.
If you want to run the task periodically then a timed background task may be appropriate. An example taken straight from the documentation is:
public class TimedHostedService : IHostedService, IDisposable
{
private int executionCount = 0;
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
var count = Interlocked.Increment(ref executionCount);
_logger.LogInformation(
"Timed Hosted Service is working. Count: {Count}", count);
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
Perform your long running task in the DoWork method. Also note that it says Timer won't wait for your long running task to finish so it may be best to stop the timer first and resume it afterwards.
Don't forget to register your background task in the ConfigureServices method of your Startup class:
services.AddHostedService<TimedHostedService>();