由于发布网站上Quartz.net的定时调度会被IIS回收不执行,解决的方法写Windows服务-案列【每天早晨8点删除过期35天的域名】
整了个三成架构:从Nuget成程序管理包下载Quart类库和TopShelf类库
1.创建定时调度Quartz类
1 class QuartzServiceRunner 2 { 3 private readonly IScheduler scheduler; 4 5 public QuartzServiceRunner() 6 { 7 scheduler = StdSchedulerFactory.GetDefaultScheduler(); 8 } 9 10 public void Start() 11 { 12 //从配置文件中读取任务启动时间 13 string cronExpr = ConfigurationManager.AppSettings["cronExpr"]; 14 IJobDetail job = JobBuilder.Create<DeleteDomainJob>().WithIdentity("job1", "group1").Build(); 15 //创建任务运行的触发器 16 ITrigger trigger = TriggerBuilder.Create() 17 .WithIdentity("triggger1", "group1") 18 .WithSchedule(CronScheduleBuilder.CronSchedule(new CronExpression(cronExpr))) 19 .Build(); 20 //启动任务 21 scheduler.ScheduleJob(job, trigger); 22 scheduler.Start(); 23 scheduler.Start(); 24 25 } 26 27 public void Stop() 28 { 29 scheduler.Clear(); 30 } 31 32 public bool Continue(HostControl hostControl) 33 { 34 scheduler.ResumeAll(); 35 return true; 36 } 37 38 public bool Pause(HostControl hostControl) 39 { 40 scheduler.PauseAll(); 41 return true; 42 } 43 44 }
2.创建从数据库中查询过期的域名执行删除方法的调度类继承IJob接口
class DeleteDomainJob : IJob { readonly ILog _log = LogManager.GetLogger(typeof(DeleteDomainJob)); public void Execute(IJobExecutionContext context) { _log.InfoFormat("域名删除调度开始******"); DomainService service = new DomainService(); int outDay = Convert.ToInt16(ConfigurationManager.AppSettings["outDay"]); List<DeleteDoaminModel> list = service.QueryDeleteDomain(outDay); StringBuilder sb = new StringBuilder(); foreach (var list_domain in list) { string str = ""; bool flag = DeleteDomainService.delete(list_domain.Domain, ref str); _log.InfoFormat("要删除的域名=" + list_domain.Domain + "到期时间=" + list_domain.EndDateUP + "订单编号=" + list_domain.DomainOrderID + "成功标志=" + flag + "返回信息=" + str); if (flag) { sb.Append("'" + list_domain.Domain + "',"); } } string str_domain = sb.ToString().TrimEnd(','); if (str_domain.Length > 0) { bool flag = service.Logic_Delete(str_domain); _log.InfoFormat("数据库删除域名===" + str_domain + "删除标志==" + flag); } } }
3.主函数入口
class Program { public static void Main(string[] args) { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); HostFactory.Run(x => { x.Service<QuartzServiceRunner>(s => { s.ConstructUsing(name => new QuartzServiceRunner()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.StartAutomatically(); x.SetDescription("开创云调度服务"); x.SetDisplayName("开创云调度服务"); x.SetServiceName("开创云调度服务"); }); } }
4.生成Windows服务
把你的项目Release生成找到解决方案所在的文件夹
找到***windowservice.exe;复制当前的路径G:TopshelfDemoTopshelfDemoinRelease****.WindowService.exe
以管理员的身份运行命令提示符窗口
安装完成找到管理工具》服务程序 即可看到