且构网

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

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

更新时间:2023-12-05 11:41:28

scheduler.getCurrentlyExecutingJobs()在大多数情况下应该工作。但请记住不要在Job类中使用它,因为它使用ExecutingJobsManager(一个JobListener)将正在运行的作业放置到在作业类之前运行的HashMap,因此使用此方法检查作业是否正在运行将肯定返回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实例中执行的作业,而不是整个集群。如果在集群中运行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.