How to check whether Quartz cron job is running?

前端 未结 3 434
梦谈多话
梦谈多话 2020-12-09 05:01

How to check if scheduled Quartz cron job is running or not? Is there any API to do the checking?

3条回答
  •  北海茫月
    2020-12-09 05:17

    scheduler.getCurrentlyExecutingJobs() should work in most case. But remember not to use it in Job class, for it use ExecutingJobsManager(a JobListener) to put the running job to a HashMap, which run before the job class, so use this method to check job is running will definitely return true. One simple approach is to check that fire times are different:

    public static boolean isJobRunning(JobExecutionContext ctx, String jobName, String groupName)
            throws SchedulerException {
        List currentJobs = ctx.getScheduler().getCurrentlyExecutingJobs();
    
        for (JobExecutionContext jobCtx : currentJobs) {
            String thisJobName = jobCtx.getJobDetail().getKey().getName();
            String thisGroupName = jobCtx.getJobDetail().getKey().getGroup();
            if (jobName.equalsIgnoreCase(thisJobName) && groupName.equalsIgnoreCase(thisGroupName)
                    && !jobCtx.getFireTime().equals(ctx.getFireTime())) {
                return true;
            }
        }
        return false;
    }
    

    Also notice that this method is not cluster aware. That is, it will only return Jobs currently executing in this Scheduler instance, not across the entire cluster. If you run Quartz in a cluster, it will not work properly.

提交回复
热议问题