.NET Core 中基于 IHostedService 实现后台定时任务
2018-09-14 18:08
716 查看
.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<TimedBackgroundService> 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<TimedBackgroundService>(); }
然后只要站点启动,就会定时输出日志:
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<TimedBackgroundService>(); }); 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
体验完成。
相关文章推荐
- .NET Core基于Generic Host实现后台任务方法教程
- 基于ServletContextListener以及TimerTask实现Java/WEB的定时任务处理
- django+xadmin+djcelery实现后台管理定时任务
- 使用ASP.NET实现Windows Service定时执行任务
- 【译】Spring 4 基于TaskScheduler实现定时任务(注解)
- 基于Java线程实现后台定时监控
- ASP.net实现WEB站点的后台定时任务+示例
- service的简单使用--后台执行的定时任务
- 基于spring+quartz的分布式定时任务框架实现
- Android中如何实现后台执行定时任务
- js实现定时任务,每隔N秒请求后台
- Android四大组件之service(二)——用service、scheduleAtFixedRate写一个后台定时执行任务
- 基于spring注解实现定时任务
- java中基于线程池和反射机制实现定时任务
- ASP.net:实现站点的后台定时任务
- android service 后台执行定时任务
- WEB后台定时任务服务类及实现 源代码
- JS实现定时任务每隔N秒请求后台setInterval定时和ajax请求问题
- ios开发视频播放后台下载功能实现 :1,ios播放视频 ,包含基于AVPlayer播放器,2,实现下载,iOS后台下载(多任务同时下载,单任务下载,下载进度,下载百分比,文件大小,下载状态)(真机调试功能正常)
- Spring定时任务的实现方式--ScheduledExecutorService and ScheduledExecutorFactoryBean的简单源码解析以及使用