使用scheduler之前應首先執行個體化它。使用SchedulerFactory可以完成scheduler的執行個體化。使用者可直接地執行個體化這個工廠類并且直接使用工廠的執行個體(例如下面的例子)。
一旦一個scheduler被執行個體化,它就可以被啟動(start),并且處于駐留模式,直到被關閉(shutdown)。注意,一旦scheduler被關閉(shutdown),則它不能再重新啟動,除非重新執行個體化它。除非scheduler 被啟動或者不處于暫停狀态,否則觸發器不會被觸發(任務也不能被執行)。
下面是一個代碼片斷,這個代碼片斷執行個體化并且啟動了一個scheduler,接着将一個要執行的任務納入了程序。
using Common.Logging;
namespace Quartz.Examples.Example1
{
/// <summary>
/// This is just a simple job that says "Hello" to the world.
/// </summary>
/// <author>Bill Kratzer</author>
public class HelloJob : IJob
{
private static ILog _log = LogManager.GetLogger(typeof(HelloJob));
/// <summary>
/// Empty constructor for job initilization
/// <p>
/// Quartz requires a public empty constructor so that the
/// scheduler can instantiate the class whenever it needs.
/// </p>
/// </summary>
public HelloJob()
{
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a
/// <see cref="Trigger" /> fires that is associated with
/// the <see cref="IJob" />.
/// </summary>
public virtual void Execute(JobExecutionContext context)
{
// Say Hello to the World and display the date/time
_log.Info(string.Format("Hello World! - {0}", System.DateTime.Now.ToString("r")));
}
}
}
ILog log = LogManager.GetLogger( typeof (SimpleExample));
log.Info( " ------- Initializing ---------------------- " );
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory();
IScheduler sched = sf.GetScheduler();
log.Info( " ------- Initialization Complete ----------- " );
log.Info( " ------- Scheduling Jobs ------------------- " );
// computer a time that is on the next round minute
DateTime runTime = TriggerUtils.GetEvenMinuteDate( new NullableDateTime(DateTime.Now));
// define the job and tie it to our HelloJob class
JobDetail job = new JobDetail( " job1 " , " group1 " , typeof (HelloJob));
// Trigger the job to run on the next round minute
SimpleTrigger trigger = new SimpleTrigger( " trigger1 " , " group1 " , runTime);
// Tell quartz to schedule the job using our trigger
sched.ScheduleJob(job, trigger);
log.Info( string .Format( " {0} will run at: {1} " , job.FullName, runTime.ToString( " r " )));
// Start up the scheduler (nothing can actually run until the
// scheduler has been started)
sched.Start();
log.Info( " ------- Started Scheduler ----------------- " );
// wait long enough so that the scheduler as an opportunity to
// run the job!
log.Info( " ------- Waiting 90 seconds
------------- " );
// wait 90 seconds to show jobs
Thread.Sleep( 90 * 1000 );
// shut down the scheduler
log.Info( " ------- Shutting Down --------------------- " );
sched.Shutdown( true );
log.Info( " ------- Shutdown Complete ----------------- " );
如您所見,使用 quartz 相當簡單,在第二課中,我們将給出一個 Job 和 Trigger 的快速預覽,這樣就能夠充分了解這個例子。