Java Quartz 调度作业 - 禁止并发执行作业

2022-09-02 11:39:43

我正在使用石英作业来执行特定任务。

我还在我的 Main 应用程序类中调度了它的执行,我试图完成的是不允许同时执行此作业的实例。

因此,计划程序应仅在其上一个实例完成时才执行作业。

这是我的工作课程:

public class MainJob implements Job {

static Logger log = Logger.getLogger(MainJob.class.getName());

@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {

    GlobalConfig cfg = new GlobalConfig();

    ProcessDicomFiles processDicomFiles = new ProcessDicomFiles();  
    ProcessPdfReportFiles processPdf = new ProcessPdfReportFiles();

    try {

            log.info("1. ---- SCHEDULED JOB -- setStudiesReadyToProcess");
            processDicomFiles.setStudiesReadyToProcess();

            log.info("2. ---- SCHEDULED JOB --- distributeToStudies");
            processDicomFiles.distributeToStudies(cfg.getAssocDir());                

            ...

            //process any incoming PDF file
            log.info("11. ---- SCHEDULED JOB --- processPdfFolder");
            processPdf.processPdfFolder();

        } catch (Exception ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.ERROR, null, ex);
        }

    log.info(">>>>>>>>>>> Scheduled Job has ended .... <<<<<<<<<<<<<<<<<<<<");

    }
}

因此,在我的应用程序的主类中,我启动了调度程序:

...
//start Scheduler
    try {             
        startScheduler();
    } catch (SchedulerException ex) {
        log.log(Level.INFO, null, ex);
    }
...

public void startScheduler () throws SchedulerException {

        //Creating scheduler factory and scheduler
        factory = new StdSchedulerFactory();
        scheduler = factory.getScheduler();

        schedulerTimeWindow = config.getSchedulerTimeWindow();

        JobDetailImpl jobDetail = new JobDetailImpl();
        jobDetail.setName("First Job");
        jobDetail.setJobClass(MainJob.class);

        SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
        simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
        simpleTrigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        simpleTrigger.setRepeatInterval(schedulerTimeWindow);
        simpleTrigger.setName("FirstTrigger");

        //Start scheduler
        scheduler.start();
        scheduler.scheduleJob(jobDetail,simpleTrigger);

}

我想防止调度程序启动第二个主作业实例,如果另一个实例仍在运行...


答案 1

只需使用作业类顶部的注释即可。@DisallowConcurrentExecution

请参阅此官方示例或有关并发作业执行的本教程


答案 2

@DisallowConcurrentExecution可以完成您的工作,但请考虑它只会防止您的类在同一节点上运行两次。

请参阅Quartz 2.2多调度程序和@DisallowConcurrentExecution中@ReneM评论


推荐