Quartz是一個Java開源的作業調度架構。官方網站:http://www.opensymphony.com/quartz/
IBM網站上有一篇簡單易懂的文章:http://www.ibm.com/developerworks/cn/java/j-quartz/
Quartz.net是從java版本移植到.net版本的。官方網站:http://quartznet.sourceforge.net/
網上找了好多教程,但沒有一篇是關於如何在ASP.NET中使用的代碼。既然它適用於任何的.net程式,當然也就適用於asp.net的web應用。
(1)在web.config中進行相關配置
<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>
</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>
另外我自己加了一個配置項:<appSettings>
<add key="cronExpr" value="0 0 8-17/1 ? * 2-6"/>
</appSettings>
(2)建立一個普通類,實現Quartz.IJob介面public class RetrieveAj2003T140Job : Quartz.IJob
{
private static DataView aj2003View;
public RetrieveAj2003T140Job()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
public void Execute(Quartz.JobExecutionContext context)
{
//throw new Exception("The method or operation is not implemented.");
//你的處理邏輯,也就是“工作”
}
}
介面非常簡單,只要在Execute()方法中進行邏輯處理就可以了。比如,讀取資料庫資料,或者是讀取電子郵件。
(3)在Global.asax檔案中啟動工作調度
這便於我們在web應用啟動時,就啟動工作調度。
<%@ Import Namespace="Quartz" %>
<script runat="server">
IScheduler sched;
void Application_Start(object sender, EventArgs e)
{
// 在應用程式啟動時啟動並執行代碼
ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();
sched = sf.GetScheduler();
JobDetail job = new JobDetail("job1", "group1", typeof(RetrieveAj2003T140Job));
string cronExpr = ConfigurationManager.AppSettings["cronExpr"];
CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1", "group1",cronExpr);
sched.AddJob(job, true);
DateTime ft = sched.ScheduleJob(trigger);
sched.Start();
}
void Application_End(object sender, EventArgs e)
{
// 在應用程式關閉時啟動並執行代碼
if (sched != null)
{
sched.Shutdown(true);
}
}
</script>
需要注意的是,當Application_End的時候,需要關閉Quartz的工作。
OK了,可以在ASP.NET中正常使用了。