[Quartz] 設定程式定時自動執行

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/

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.