1.spring注解方式
@Component @EnableScheduling public class DynamicCronTask { // 每隔10秒执行一次 @Scheduled(cron = "0/10 * * * * ?") public void task(){ System.out.println("running " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
缺点:修改cron表达式,要重启服务
2.动态修改cron
@Component @EnableScheduling public class DynamicCronTask implements SchedulingConfigurer { /** * 修改了cron表达式不能立马生效 * 要等到前一个周期执行 * 新的周期才能生效 * @param scheduledTaskRegistrar */ @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { // 数据库或者缓存获取执行周期 String cron = "0/5 * * * * ? "; scheduledTaskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { System.out.println("running " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { return new CronTrigger(cron).nextExecutionTime(triggerContext); } }); } }
缺点:修改了cron表达式不能立马生效,要等到前一个周期执行触发之时,新的周期才能生效
3.动态cron,立刻生效
3.1依赖
<!--quartz--> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency>
3.2任务
public class MyJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("running " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
3.3Quartz增加任务、删除任务、修改触发时间
public class QuartzManager { private static SchedulerFactory schedulerFactory = new StdSchedulerFactory(); /** * @Description: 添加一个定时任务 * * @param jobName 任务名 * @param jobGroupName 任务组名 * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param jobClass 任务 * @param cron 时间设置,参考quartz说明文档 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cron) { try { Scheduler sched = schedulerFactory.getScheduler(); // 任务名,任务组,任务执行类 JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build(); // 触发器 TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger(); // 触发器名,触发器组 triggerBuilder.withIdentity(triggerName, triggerGroupName); triggerBuilder.startNow(); // 触发器时间设定 triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron)); // 创建Trigger对象 CronTrigger trigger = (CronTrigger) triggerBuilder.build(); // 调度容器设置JobDetail和Trigger sched.scheduleJob(jobDetail, trigger); // 启动 if (!sched.isShutdown()) { sched.start(); } } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description: 修改一个任务的触发时间 * * @param jobName * @param jobGroupName * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param cron 时间设置,参考quartz说明文档 */ public static void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName, String cron) { try { Scheduler sched = schedulerFactory.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName); CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey); if (trigger == null) { return; } String oldTime = trigger.getCronExpression(); if (!oldTime.equalsIgnoreCase(cron)) { /** 方式一 :调用 rescheduleJob 开始 */ // 触发器 TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger(); // 触发器名,触发器组 triggerBuilder.withIdentity(triggerName, triggerGroupName); triggerBuilder.startNow(); // 触发器时间设定 triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron)); // 创建Trigger对象 trigger = (CronTrigger) triggerBuilder.build(); sched.rescheduleJob(triggerKey, trigger); /** 方式二:先删除,然后在创建一个新的Job */ /*JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName)); Class<? extends Job> jobClass = jobDetail.getJobClass(); removeJob(jobName, jobGroupName, triggerName, triggerGroupName); addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, cron);*/ } } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description: 移除一个任务 * * @param jobName * @param jobGroupName * @param triggerName * @param triggerGroupName */ public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) { try { Scheduler sched = schedulerFactory.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName); sched.pauseTrigger(triggerKey);// 停止触发器 sched.unscheduleJob(triggerKey);// 移除触发器 sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));// 删除任务 } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description:启动所有定时任务 */ public static void startJobs() { try { Scheduler sched = schedulerFactory.getScheduler(); sched.start(); } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description:关闭所有定时任务 */ public static void shutdownJobs() { try { Scheduler sched = schedulerFactory.getScheduler(); if (!sched.isShutdown()) { sched.shutdown(); } } catch (Exception e) { throw new RuntimeException(e); } } }
public class MyQuartz { public static String JOB_NAME = "JOB"; public static String TRIGGER_NAME = "TRIGGER"; public static String JOB_GROUP_NAME = "JOB_GROUP"; public static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP"; public static void main(String[] args) { try { System.out.println("【系统启动】开始(每1秒输出一次)..."); QuartzManager.addJob(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, MyJob.class, "0/1 * * * * ?"); Thread.sleep(5000L); System.out.println("【修改时间】开始(每5秒输出一次)..."); QuartzManager.modifyJobTime(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME, "0/5 * * * * ?"); Thread.sleep(15 * 1000L); System.out.println("【移除定时】开始..."); QuartzManager.removeJob(JOB_NAME, JOB_GROUP_NAME, TRIGGER_NAME, TRIGGER_GROUP_NAME); System.out.println("【移除定时】成功"); } catch (Exception e) { e.printStackTrace(); } } }