.Net Core构建后台定时服务
作者:互联网
在.Net Core2.1版本中,新增了一个名为BackgroundService
的类,隶属于Microsoft.Extensions.Hosting
命名空间,用来创建后台任务服务,比如定时推送数据与接收消息等。现在我们来实现一个简单的定时任务。
注册服务
首先我们先在Startup
中注册该服务。
services.AddSingleton<IHostedService,TimedExecutService>()
其中TimedExecutService
是我们基于继承BackgroundService
新建的定时任务类。
实现接口
BackgroundService
接口提供了三个方法,分别是ExecuteAsync(CancellationToken)
,StartAsync(CancellationToken)
,StopAsync(CancellationToken)
。TimedExecutService
可以通过重载这三个方法来实现业务开发。
public class TimedExecutService : BackgroundService
{
private readonly ILogger<TimedExecutService> logger;
private readonly TimedExecutServiceSettings settings;
public TimedExecutService(IOptions<TimedExecutServiceSettings> settings, ILogger<TimedExecutService> logger)
{
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogDebug($"TimedExecutService is starting.");
stoppingToken.Register(() => logger.LogDebug($"TimedExecutService is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
logger.LogDebug($"TimedExecutService doing background work.");
//Doing Somethings
await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
}
logger.LogDebug($"TimedExecutService is stopping.");
}
protected override async Task StopAsync (CancellationToken stoppingToken)
{
// Doing Somethings
}
}
至此,一个定时任务服务已经开发完成,赶紧去试试吧。
标签:Core,CancellationToken,stoppingToken,BackgroundService,TimedExecutService,Net,Lo 来源: https://blog.csdn.net/zhanglong_longlong/article/details/120697338