上一次写了一遍关于Quartz作业调度的文章
现在使用TopShelf和Quartz实现windows服务作业调度
TopShelf版本4.0
Quartz版本3.0.6
任务文件和上次文章的一样将日期写入txt文件中,TimeJob代码如下
public class TimeJob : IJob { public Task Execute(IJobExecutionContext context) { string filePath = @"D:\\log.txt"; File.AppendAllText(filePath, DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + Environment.NewLine); Console.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + Environment.NewLine); return Task.FromResult(true); } }
1.创建调度器工厂 ISchedulerFactory factory = new StdSchedulerFactory();
2.创建任务调度器 IScheduler scheduler = null;
3.创建任务和触发器
scheduler = await factory.GetScheduler();
//创建一个任务 IJobDetail job = JobBuilder.Create<TimeJob>().WithIdentity("myJob1", "group1").Build(); //创建一个触发器 ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger1", "group1").StartNow(). WithSimpleSchedule(a => a.WithIntervalInSeconds(10).RepeatForever()).Build(); //将任务和触发器添加到调度器里 await scheduler.ScheduleJob(job, trigger);4.开始执行 scheduler.Start()
Manager代码如下
public class Manager { //创建调度器工厂 ISchedulerFactory factory = new StdSchedulerFactory(); //创建调度器 IScheduler scheduler = null; public Manager() { Init(); } private async void Init() { scheduler = await factory.GetScheduler(); //创建一个任务 IJobDetail job = JobBuilder.Create().WithIdentity("myJob1", "group1").Build(); //创建一个触发器 ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger1", "group1").StartNow(). WithSimpleSchedule(a => a.WithIntervalInSeconds(10).RepeatForever()).Build(); //将任务和触发器添加到调度器里 await scheduler.ScheduleJob(job, trigger); } public async void Start() { //开始执行 await scheduler.Start(); } public async void Stop() { //停止 await scheduler.Shutdown(false); } public async void Pause() { //暂停 await scheduler.PauseAll(); } public async void Continue() { //继续 await scheduler.ResumeAll(); } }
5.调用
static void Main(string[] args) { var fac = HostFactory.New(x => { x.Service(s => { s.ConstructUsing(name => new Manager()); s.WhenStarted(m => m.Start()); s.WhenStopped(m => m.Stop()); s.WhenPaused(m => m.Pause()); s.WhenContinued(m => m.Continue()); }); x.RunAsLocalSystem(); x.SetDescription("QuartzTopShelfDemo Windows服务"); x.SetDisplayName("QuartzTopShelfDemo 服务"); x.SetServiceName("QuartzTopShelfDemoService"); }); fac.Run(); Console.ReadKey(); }
配置安装服务
安装:TopshelfDemo.exe install
启动:TopshelfDemo.exe start
卸载:TopshelfDemo.exe uninstall
参考:https://topshelf.readthedocs.io/en/latest/configuration/config_api.html#service-name