第一种方式BackgroundService
基于后台服务类BackgroundService实现,类所在命名空间Microsoft.Extensions.Hosting;添加定时服务类,示例如下
public class ServerTimeA : BackgroundService
{
private readonly ILogger logger;
public ServerTimeA(ILogger logger)
{
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
this.logger.LogInformation("StartA");
while (!stoppingToken.IsCancellationRequested)
{
this.logger.LogWarning("DoworkA...");
await Task.Delay(2000, stoppingToken);
}
this.logger.LogInformation("EndA...");
}
}
public class ServerTimeB : BackgroundService
{
private readonly ILogger logger;
public ServerTimeB(ILogger logger)
{
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
this.logger.LogInformation("StartB");
while (!stoppingToken.IsCancellationRequested)
{
this.logger.LogWarning("DoworkB...");
await Task.Delay(3000, stoppingToken);
}
this.logger.LogInformation("EndB...");
}
}
然后在Startup类中的ConfigureServices方法中添加
services.AddHostedService();
services.AddHostedService();
第二种方式Hangfire
第三种方式quarzt
第三种方式TimedJob