在我们平时做开发的时候,时常会用到定时任务触发某个特定逻辑业务以便数据能及时更新
如果你不想用Windows服务, 可以使用Quartz.Net在项目中编写定时任务调度,简简单单几行代码就能搞定。
简介:想要定时抓取、定时更新数据又不想使用windows服务,Quartz.Net组件将会是你最好的选择。
下面来看下Quartz.Net使用方法,下面的DEMO只针对Quartz使用做出详细说明,程序中一些其他逻辑没编写,请自行领悟。
Quartz Cron表达式在线生成工具
1,将Quartz.dll引用到项目后,先在Web.config中configuration节点中设置定时所需节点
02 | <section name= "quartz" type= "System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" /> |
05 | <add key= "quartz.scheduler.instanceName" value= "ExampleDefaultQuartzScheduler" /> |
07 | <add key= "quartz.threadPool.type" value= "Quartz.Simpl.SimpleThreadPool, Quartz" /> |
08 | <add key= "quartz.threadPool.threadCount" value= "10" /> |
09 | <add key= "quartz.threadPool.threadPriority" value= "2" /> |
11 | <add key= "quartz.jobStore.misfireThreshold" value= "60000" /> |
12 | <add key= "quartz.jobStore.type" value= "Quartz.Simpl.RAMJobStore, Quartz" /> |

2,编写定时任务,处理定时逻辑
02 | using System.Collections.Generic; |
09 | public class TimeJob : IJob |
16 | /// <param name="context"></param> |
17 | public void Execute(IJobExecutionContext context) |
20 | PostHelper.HttpPostData(); |
3,在Global.asax中启动当时任务、处理定时周期等参数
02 | using System.Collections.Generic; |
05 | using System.Web.Security; |
06 | using System.Web.SessionState; |
12 | public class Global : System.Web.HttpApplication |
18 | /// <param name="sender"></param> |
19 | /// <param name="e"></param> |
20 | protected void Application_Start( object sender, EventArgs e) |
22 | ISchedulerFactory sf = new StdSchedulerFactory(); |
23 | IScheduler scheduler = sf.GetScheduler(); |
24 | IJobDetail job = JobBuilder.Create<TimeJob>().WithIdentity( "job1" , "mygroup" ).Build(); |
25 | ITrigger trigger = TriggerBuilder.Create().StartAt(DateTime.Now.AddSeconds(5)).WithCronSchedule( "/2 * * ? * *" ).Build(); |
26 | scheduler.ScheduleJob(job, trigger); |
30 | protected void Session_Start( object sender, EventArgs e) |
35 | protected void Application_BeginRequest( object sender, EventArgs e) |
40 | protected void Application_AuthenticateRequest( object sender, EventArgs e) |
45 | protected void Application_Error( object sender, EventArgs e) |
50 | protected void Session_End( object sender, EventArgs e) |
55 | protected void Application_End( object sender, EventArgs e) |
4,大功告成,只要编写没问题,程序启动后,在设定的时间周期内此定时任务就会按照时间周期去定时触发。
如有不理解的,可以下载DEMO源码体验一下,为了更清晰看到执行周期,请自行添加日志文件记录执行记录。
C#使用Quartz.Net实现定时作业定时任务DEMO源码
原文链接C#使用Quartz.Net实现定时作业定时任务DEMO源码