package com.monkeylessey.job.utis;
|
|
import com.monkeylessey.enums.general.JobStatusEnum;
|
import com.monkeylessey.job.domain.entity.SysJob;
|
import org.quartz.*;
|
|
/**
|
* @author 29443
|
* @date 2022/6/9
|
*/
|
public class JobUtil {
|
|
/**
|
* 创建定时任务
|
*
|
* @param scheduler
|
* @param job
|
* @throws ClassNotFoundException
|
* @throws SchedulerException
|
*/
|
public static void createJob(Scheduler scheduler, SysJob job) throws ClassNotFoundException, SchedulerException {
|
// 获取jib类的Class
|
Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(job.getJobClass());
|
|
// 创建任务实例
|
JobDetail jobDetail = JobBuilder.newJob(jobClass)
|
.withIdentity(job.getJobKey(), job.getJobGroup())
|
.build();
|
// 创建触发器
|
CronTrigger trigger = TriggerBuilder.newTrigger()
|
.forJob(job.getJobKey(), job.getJobGroup())
|
.withIdentity(job.getJobKey(), job.getJobGroup())
|
.withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpress()))
|
.build();
|
|
// 如果任务存在,删除再添加
|
checkAndDeleteJob(scheduler, job);
|
scheduler.scheduleJob(jobDetail, trigger);
|
// 判断任务是否暂停状态
|
if (JobStatusEnum.OFF.equals(job.getJobStatus())) {
|
scheduler.pauseJob(new JobKey(job.getJobKey(), job.getJobGroup()));
|
}
|
}
|
|
/**
|
* 执行一次定时任务
|
*
|
* @param job
|
*/
|
public static void executeOnce(Scheduler scheduler, SysJob job) throws SchedulerException {
|
scheduler.triggerJob(new JobKey(job.getJobKey(), job.getJobGroup()));
|
}
|
|
/**
|
* 暂停定时任务
|
*
|
* @param scheduler
|
* @param job
|
*/
|
public static void stopJob(Scheduler scheduler, SysJob job) throws SchedulerException {
|
scheduler.pauseJob(new JobKey(job.getJobKey(), job.getJobGroup()));
|
}
|
|
/**
|
* 启动定时任务
|
*
|
* @param scheduler
|
* @param job
|
*/
|
public static void startJob(Scheduler scheduler, SysJob job) throws SchedulerException {
|
scheduler.resumeJob(new JobKey(job.getJobKey(), job.getJobGroup()));
|
}
|
|
/**
|
* 检查任务是否存在,存在则删除该任务
|
*
|
* @param scheduler
|
* @param job
|
* @throws SchedulerException
|
*/
|
public static void checkAndDeleteJob(Scheduler scheduler, SysJob job) throws SchedulerException {
|
if (scheduler.checkExists(new JobKey(job.getJobKey(), job.getJobGroup()))) {
|
deleteJob(scheduler, job);
|
}
|
}
|
|
/**
|
* 删除定时任务
|
*
|
* @param scheduler
|
* @param job
|
* @throws SchedulerException
|
*/
|
public static void deleteJob(Scheduler scheduler, SysJob job) throws SchedulerException {
|
scheduler.deleteJob(new JobKey(job.getJobKey(), job.getJobGroup()));
|
}
|
}
|