core 2.0中通过实现IHostedService接口实现后台任务
public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); }
core2.1开始,提供了一个继承IHostedService接口的实现类BackgroundService。
我们通过实现抽象类BackgroundService来实现后台任务
public class TimeBackgroundWorks : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) {
//此处需要校验stoppingToken.IsCancellationRequested Timer timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(3)); return Task.CompletedTask; } private void DoWork(Object state) { Console.WriteLine("DoWork"); } }
ConfigureService中添加:
services.AddHostedService<TimeBackgroundWorks>();
参考:https://www.cnblogs.com/viter/p/10078488.html
...