在多实例环境中仅执行一次Quartz Job

时间:2019-08-06 00:04:29

标签: java quartz-scheduler quartz

我正在尝试在Quartz 1.6中创建一个Job,但是只需要执行一次,因为我有两个测试实例具有相同版本的.war文件。

这是我的TestPlugin类,Job每60秒执行一次:

public class TestPlugin implements PlugIn {

    public TestPlugin() {
        super();
    }

    public void destroy() {
    }

    public void init(ActionServlet arg0, ModuleConfig arg1)
            throws ServletException {

        try {
            JobDetail job = JobBuilder.newJob(TestDemonio.class)
                    .withIdentity("anyJobName", "group1").build();
            Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("anyTriggerName", "group1")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/60 * * ? * * *"))
                    .build();

            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.scheduleJob(job, trigger);
            scheduler.start();

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

然后我有我的课程TestExecute来打印简单的输出:

@DisallowConcurrentExecution
public class TestDemonio implements Job {

    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        System.out.println("QUARTZ JOB MESSAGE");
    }
}

我已经研究了如何通过添加批注@DisallowConcurrentExecution来实现我想要的功能,该批注仅执行一次作业,但是我收到在每个实例上打印的消息。

这是我的crystal.properties文件:

# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

1 个答案:

答案 0 :(得分:1)

您需要将以下属性添加到quartz.property文件中(源:click here):

org.quartz.jobStore.isClustered : true

阅读此书以获取有关isClustered属性的更多信息,请参考this链接。

请注意:

@DisallowConcurrentExecution在您有2个不同的作业且在相同节点上运行相同作业密钥时起作用。

使用isClustered属性可确保当应用程序运行通过数据库表进行通信的多个节点的原子性时,将执行作业的单个实例。