在.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
}
}
至此,一个定时任务服务已经开发完成,赶紧去试试吧。
本文介绍了在.NetCore2.1中如何利用BackgroundService创建后台任务服务,特别是用于定时任务的场景。首先在Startup配置文件中注册服务,然后创建一个继承自BackgroundService的TimedExecutService类,重写ExecuteAsync、StartAsync和StopAsync方法以实现业务逻辑。在ExecuteAsync方法中,通过循环和Task.Delay实现定时任务的执行。最后,当接收到停止信号时,执行StopAsync方法进行清理工作。
401

被折叠的 条评论
为什么被折叠?



