这周接受到一个新的需求:一天内分时间段定时轮询一个第三方WebAPI,并保存第三方WebAPI结果。
需求分析:分时段、定时开启、定时结束、轮询。主要工作集中在前三个上,轮询其实就是个Http请求,比较好解决。
技术选型:
1、最简单的方式:Windows Service、Timer、HttpClient。
2、B格高点的方式:Topshelf、Quartz.NET、HttpClient。
之所以选用第二种方式的原因:
1、Windows Service尝试写了一个,发现附加进程调试确实麻烦,而且以后若是需求变更,还需要重新调试发布Windows Service
2、Timer需要在项目中建立多个,区分起来着实麻烦
3、刚好在学习使用Quartz.NET,打算过段时间做个MVC版本的调度任务管理系统
4、经过查找cnblog发现,使用Topshelf可以用基于Console的模式先编写、调试程序,等调试通过后,用Topshelf命令即可完成Windows Service安装,据说还可以在Linux上通过Mono安装,也算是可以支持跨平台的咯(*^_^*)或许也可以通过制作Docker镜像来实现。
Show Code:
1、添加依赖Nuget包:Topshelf、Topshelf.Log4Net、Quartz、Common.Logging、Common.Logging.Core、Common.Logging.Log4Net1211、log4Net
2、创建ServiceRunner.cs类,继承ServiceControl, ServiceSuspend,这是为了用Topshelf的Start()、Stop()、Continue()、Pause()来分别执行Quartz任务调度的Start()、Shutdown()、ResumeAll()、PauseAll()方法
1 public class ServiceRunner : ServiceControl, ServiceSuspend 2 { 3 private readonly IScheduler scheduler; 4 public ServiceRunner() 5 { 6 scheduler = StdSchedulerFactory.GetDefaultScheduler(); 7 } 8 public bool Continue(HostControl hostControl) 9 { 10 scheduler.ResumeAll(); 11 return true; 12 } 13 14 public bool Pause(HostControl hostControl) 15 { 16 scheduler.PauseAll(); 17 return true; 18 } 19 20 public bool Start(HostControl hostControl) 21 { 22 scheduler.Start(); 23 return true; 24 } 25 26 public bool Stop(HostControl hostControl) 27 { 28 scheduler.Shutdown(false); 29 return true; 30 } 31 }