只是为了记录下,为以后需要的时候有个参考。
版本:Quartz 2.x
导入依赖包
import static org.quartz.TriggerBuilder.newTrigger;import org.quartz.CronScheduleBuilder;import org.quartz.CronTrigger;import org.quartz.JobBuilder;import org.quartz.JobDataMap;import org.quartz.JobDetail;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.quartz.Scheduler;import org.quartz.SchedulerException;import org.quartz.SchedulerFactory;import org.quartz.impl.StdSchedulerFactory;
调度的创建:
public static Scheduler scheduler;//定时调度时间配置。每小时15分的时候执行String scheCronExpress = "0 0/15 * * * ?";static { // 静止检查更新 System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true"); SchedulerFactory sf = new StdSchedulerFactory(); try { scheduler = sf.getScheduler(); scheduler.start(); } catch (Exception e) { e.printStackTrace(); }}
创建用于执行的Job
/** * 定时调度执行类 * */ public class ScheduleJob implements org.quartz.Job { public void execute(JobExecutionContext context) throws JobExecutionException { Date filreTime = context.getFireTime(); JobDataMap dataMap = context.getMergedJobDataMap(); //TODO 调度时候执行的逻辑代码 } }
添加调度任务
public void addCronJob(String cronexpress){ String groupName = UUID.randomUUID().toString(); JobDataMap newJobDataMap = new JobDataMap(); newJobDataMap.put("outer", this); // 创建Job JobDetail job = JobBuilder.newJob(ScheduleJob.class) .withIdentity("job-" + groupName, groupName) .usingJobData(newJobDataMap) .build(); // 构建触发器 CronTrigger trigger = newTrigger().withIdentity("trigger-" + groupName, groupName) .withSchedule(CronScheduleBuilder.cronSchedule(cronexpress)) .build(); //任务和触发器关联 scheduler.scheduleJob(job, trigger);}