代码改变世界

Quartz.net2.1使用笔记

2013-03-25 02:11  lofe  阅读(792)  评论(0编辑  收藏  举报

使用Quartz.net2.1.2.4创建一个作业计划,想法是每几秒执行,但每次执行时,都是接着上次执行任务完成后再执行下一遍任务。但创建了Triiger后,当前一个任务在相隔的时间里没有完成时,紧接着另一个定时执行的任务又开始执行了,就存在同一时间有两个相同的任务在并行执行,不是希望的结果。

private void button1_Click(object sender, EventArgs e)
        {
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();
            IJobDetail job = JobBuilder.Create<HelloJob>().WithIdentity("job1", "group1").Build();
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1", "group1").WithCronSchedule("0/1 * * * * ?").Build();
            sched.ScheduleJob(job, trigger);
            sched.Start();
        }

 

在网上搜索了一下,描述要从原来的IJob接口改为继承另一个有状态接口(IStatefulJob)。当继承它后,提示已过期,让使用DisallowConcurrentExecution/PersistJobDataAfterExecution的属性标签,看来在新的的版本里架构做了较大的改变。

于是还是改为原来继承的IJob接口,在类里加入标签[PersistJobDataAfterExecution]和[DisallowConcurrentExecution],测试通过,达到效果。

    [PersistJobDataAfterExecution]
    [DisallowConcurrentExecution]
    public class HelloJob:IJob
    {
        public static ILog _log = LogManager.GetLogger(typeof(HelloJob));
        public void Execute(IJobExecutionContext context)
        {
            Thread.Sleep(TimeSpan.FromSeconds(3));
            MessageBox.Show("ok");
        }
    }