第一步:下载Quartz.NET类库源码
下载地址:http://www.quartz-scheduler.net/
第二步:程序集成:
1.修改网站根目录下的web.config文件,在configuration节增加:
<configSections>
<!--定时任务调度配置-->
<section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<!--/End 定时任务调度配置-->
</configSections>
<!--定时任务调度配置-->
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
<arg key="showLogName" value="true" />
<arg key="showDataTime" value="true" />
<arg key="level" value="DEBUG" />
<arg key="dateTimeFormat" value="HH:mm:ss:fff" />
</factoryAdapter>
</logging>
</common>
<quartz>
<add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler" />
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
<add key="quartz.threadPool.threadCount" value="10" />
<add key="quartz.threadPool.threadPriority" value="2" />
<add key="quartz.jobStore.misfireThreshold" value="60000" />
<add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
</quartz>
<!--/End 定时任务调度配置-->
注意:如果web.config已存在configSections节,请将configSections节内的配置复制到web.config的configSections节下。
2.编写代码:
public class Scheduler { private static IScheduler _instance; private Scheduler() { } /// <summary> /// 获得本类实例的唯一全局访问点。 /// </summary> /// <returns></returns> [CLSCompliant(false)] public static IScheduler GetIntance() { if (_instance == null) { ISchedulerFactory schedFact = new StdSchedulerFactory(); _instance = schedFact.GetScheduler(); } return _instance; } }
public class JobHelper { #region 命名前缀(可以自行设置) /// <summary> /// 作业前缀 /// </summary> public static string JobPerfix = "Job_"; /// <summary> /// 作业分组前缀 /// </summary> public static string GroupPerfix = "Group_"; /// <summary> /// 作业触发器前缀 /// </summary> public static string TriggerPerfix = "Trigger_"; #endregion #region 初始化作业实体 /// <summary> /// 根据传入类型初始化作业实体 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static JobKey GetJobKey<T>() { string name = typeof(T).FullName; return new JobKey(JobPerfix+name, GroupPerfix+name); } #endregion #region 开启作业 /// <summary> /// 开启作业 /// </summary> /// <param name="expression">表达式 /// <returns></returns> public static bool StartJob<T>(string expression) where T : IJob { string name = typeof (T).FullName; IJobDetail job = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>()); if (job != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name)) { return true; } if (!Scheduler.GetIntance().IsStarted) { Scheduler.GetIntance().Start(); } if (job != null) { Scheduler.GetIntance().ResumeJob(GetJobKey<T>()); } else { IJobDetail detail = JobBuilder.Create<T>().WithIdentity(JobPerfix+name, GroupPerfix+name).Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity(TriggerPerfix+name) .StartNow() .WithCronSchedule(expression).ForJob(detail) .Build(); Scheduler.GetIntance().ScheduleJob(detail, trigger); return true; } return false; } #endregion #region 停止作业 /// <summary> /// 停止作业 /// </summary> /// <returns></returns> public static bool StopJob<T>() { string name = typeof (T).FullName; IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>()); if (detail != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name)) { Scheduler.GetIntance().PauseJob(GetJobKey<T>()); return true; } return false; } #endregion #region 删除作业 /// <summary> /// 删除作业 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static bool DelJob<T>() { string name = typeof (T).FullName; IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>()); if (detail != null&&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name)) { Scheduler.GetIntance().PauseJob(GetJobKey<T>()); Scheduler.GetIntance().DeleteJob(GetJobKey<T>()); return true; } return false; } #endregion #region 取得作业运行状态 /// <summary> /// 取得作业运行状态 true 正在运行,false 未在运行 /// </summary> /// <returns></returns> public static bool GetJobStatus<T>() { string name = typeof(T).FullName; IJobDetail detail = Scheduler.GetIntance().GetJobDetail(GetJobKey<T>()); if (detail != null && !Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+name)) { return true; } return false; } public static bool GetJobStatus(string jobName) { string className = jobName.Substring(JobPerfix.Length); IJobDetail detail = Scheduler.GetIntance().GetJobDetail(new JobKey(jobName, GroupPerfix+className)); if (detail != null &&!Scheduler.GetIntance().IsJobGroupPaused(GroupPerfix+className)) { return true; } return false; } #endregion }
public class MyJob : IJob { public void Execute(IJobExecutionContext context) { ClsLogs log = new ClsLogs(); log._logEvent("Hello at " + DateTime.Now.ToString(),"E:\\svn项目源码\\平行世界svn\\trunk\\ParalWorld\\ParalWorld.Wenxin\\Log"); } }
3.在网站Global.asax文件的Application_Start事件里开启定时任务:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//开启定时任务调度
JobHelper.StartJob<MyJob>("0 0/1 * * * ?");//每隔一分钟执行一次任务
}
至此程序集成完毕,可以根据自己设定的表达式触发器来检验定时任务是否正常工作。
参考文档:
1.Quartz.NET 官网:http://www.quartz-scheduler.net/documentation/index.html
2.简单触发器:http://www.quartz-scheduler.net/documentation/quartz-2.x/quick-start.html
3.表达式触发器:http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html
Global.asax 可以是asp.net中应用程序或会话事件处理程序,我们用到了Application_Start(应用程序开始事件)和Application_End(应用程序结束事件)。当应用程序开始时,启动一个定时器,用来定时执行任务YourTask()方法,这个方法里面可以写上需要调用的逻辑代码,可以是单线程和多线程。当应用程序结束时,如IIS的应用程序池回收,让asp.net去访问当前的这个web地址。这里需要访问一个aspx页面,这样就可以重新激活应用程序。
protected
void
Application_End(
object
sender, EventArgs e)
{
//下面的代码是关键,可解决IIS应用程序池自动回收的问题
Thread.Sleep(1000);
//这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
string
url = "http://www.baidu.com"
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();
//得到回写的字节流
}