您现在的位置是: 首页 > .NET CORE > 文章详情 文章详情
.NET Core 中基于 IHostedService 实现后台定时任务
2019-08-19 【.NET CORE】 2353人浏览
.NET Core 2.0 引入了 IHostedService ,基于它可以很方便地执行后台任务,.NET Core 2.1 则锦上添花地提供了 IHostedService 的默认实现基类 BackgroundService ,在这篇随笔中分别用 Web 与 Console 程序体验一下。
首先继承 BackgroundService 实现一个 TimedBackgroundService
public class TimedBackgroundService : BackgroundService{ private readonly ILogger _logger; private Timer _timer; public TimedBackgroundService(ILogger logger) {
_logger = logger;
} protected override Task ExecuteAsync(CancellationToken stoppingToken) {
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask;
} private void DoWork(object state) {
_logger.LogInformation($"Hello World! - {DateTime.Now}");
} public override void Dispose() { base.Dispose();
_timer?.Dispose();
}
}
在 ASP.NET Core Web 程序中执行这个后台定时任务只需在 Startup 的 ConfigureServices 注册 TimedBackgroundService 即可:
public void ConfigureServices(IServiceCollection services){
services.AddHostedService();
}
然后只要站点启动,就会定时输出日志:
Now listening on: http://localhost:5000 Application started. Press Ctrl+C to shut down. info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:48:02 info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:48:07 info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:48:12
接下来在控制台程序中体验一下。
基于 Generic Host 实现如下的控制台程序,也是执行在 ConfigureServices 中注册一下 TimedBackgroundService 。
class Program{ public static async Task Main(string[] args) { var builder = new HostBuilder()
.ConfigureLogging(logging =>
{
logging.AddConsole();
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService();
}); await builder.RunConsoleAsync();
}
}
dotnet run 运行程序后 TimedBackgroundService 定时输出了日志:
info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:59:37 info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:59:42 info: BackgroundServiceSample.Services.TimedBackgroundService[0] Hello World! - 9/14/2018 17:59:47
体验完成。
很赞哦! (0)
相关文章

热门收藏
- .net core Redis分布式缓存的客户端实现
- .net core API 统一拦截错误
- ASP.NET Core MVC中的IActionFilter.OnActionExecuted方法执行时,Controller中Action返回的对象是否已经输出到Http Response中
- aspnet core 2.1中使用jwt从原理到精通一
- aspnet core 2.1中使用jwt从原理到精通二
- aspnet core 2.1中使用jwt从原理到精通三
- ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统
- 消除 ASP.NET Core 告警 "No XML encryptor configured. Key may be persisted to storage in unencrypted form
- .NET Core 中基于 IHostedService 实现后台定时任务
- 【.Net Core】获取绝对路径、相对路径