Quartz 是一個scheduler API, 可以讓program 於指定時間, 自動執行指令. 相對使用windows的schedule job 或Linux 的cron job, 它少了OS level 的dependency, 即是無須設定執行schedule job 的user account 等.
使用時, 須要implement 其Interface IJob.
public class CheckUnsentEmailJob : IJob { public override void Execute(IJobExecutionContext context) { // Execute schedule actual task. }
而在static void main() 或global.asax 中, 須要進行以下的編碼.
private IScheduler _schedular = null; protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Create schedule job and execute. StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); _schedular = schedulerFactory.GetScheduler(); IJobDetail job = JobBuilder.Create<CheckUnsentEmailJob>() .WithIdentity(typeof(CheckUnsentEmailJob).Name) .Build(); ITrigger trigger = TriggerBuilder.Create() .WithCronSchedule(ConfigurationManager.AppSettings["CheckUnsentEmailJobScheduleExpression"]) .WithIdentity(typeof(CheckUnsentEmailJob).Name + "_trigger") .Build(); _schedular.ScheduleJob(job, trigger); _schedular.Start(); } protected void Application_End(object sender, EventArgs e) { _schedular.Shutdown(false); }
若想知道更多, 可以參考其官網.
Quartz Job Scheduler:
https://www.quartz-scheduler.org/
Leave a Reply