且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查 Quartz cron 作业是否正在运行?

更新时间:2023-12-05 11:49:34

scheduler.getCurrentlyExecutingJobs() 在大多数情况下应该可以工作.但是切记不要在Job类中使用它,因为它使用ExecutingJobsManager(a JobListener)将正在运行的Job放到一个HashMap中,HashMap在Job类之前运行,所以用这个方法检查Job是否正在运行肯定会返回true.一种简单的方法是检查触发时间是否不同:

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<JobExecutionContext> 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;
}

另请注意,此方法不是集群感知的.也就是说,它只会返回当前在这个 Scheduler 实例中执行的 Jobs,而不是整个集群.如果在集群中运行 Quartz,它将无法正常工作.

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.