1.在pom.xml文件中下载插件
<!-- Quartz定时任务 --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> </dependency> <!--json--> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20180813</version> </dependency>
2.新建个包utils,在包下建这两个类:直接copy即可
package org.boot.city.utils; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; /** * @Description:定时任务工具类:新增任务,修改任务时间,删除任务,启动所有任务,停止所有任务 * @since 2019年10月22日18:45:23 */ public class QuartzUtil { private static SchedulerFactory schedulerFactory = new StdSchedulerFactory(); /** * @param jobName 任务名 * @param jobGroupName 任务组名 * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param jobClass 任务 * @param cron 时间设置,参考quartz说明文档 * @Description: 添加一个定时任务 */ @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); } } /** * @param jobName * @param jobGroupName * @param triggerName 触发器名 * @param triggerGroupName 触发器组名 * @param cron 时间设置,参考quartz说明文档 * @Description: 修改一个任务的触发时间 */ 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); /** 方式一 :调用 rescheduleJob 结束 */ /** 方式二:先删除,然后在创建一个新的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); } } /** * @param jobName * @param jobGroupName * @param triggerName * @param triggerGroupName * @Description: 移除一个任务 */ 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); } } }
package org.boot.city.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Spring工具类 * 在非spring生命周期的地方使用javabean */ @SuppressWarnings("unchecked") @Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext appContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { appContext = applicationContext; } public static ApplicationContext getApplicationContext() { return appContext; } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name, Class<T> clazz) throws BeansException { return (T) appContext.getBean(name); } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } }
3. 新建包job,在包下创建job类
注意:具体操作相当于也是业务层,较规范的做法是job类最终也经过service层,然后再进入mapper
package org.boot.city.job; import org.boot.city.entity.MessagePush; import org.boot.city.entity.Points; import org.boot.city.gustdata.Main; import org.boot.city.service.MessagePushService; import org.boot.city.utils.SpringContextUtil; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; import java.util.Map; public class PushJob implements Job { private static final Logger logger = LoggerFactory.getLogger(PushJob.class);//创建日志对象 @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.info("===================任务开始执行===================:" + new Date()); //获取bean对象; /** * @Service("mpm") public class MessagePushServiceImpl implements MessagePushService { */ MessagePushService messagePushService = SpringContextUtil.getBean("mpm", MessagePushService.class); //...具体操作 logger.info("===================任务执行完成===================:"+ new Date()); } }
4.在springboot 启动类中设置定时任务时间
注意:如果不知道如何写时间,可以搜索corn,或者点击https://cron.qqe2.com/,可以自动计算出corn表达式。
package org.boot.city; import org.boot.city.job.PushJob; import org.boot.city.utils.QuartzUtil; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CityApplication { private static String week = "0 0 0 1/7 * ? "; //定时时间测试,每个小时的第48分钟执行该任务 private static String tttttt = "50 48 0/1 * * ? "; public static void main(String[] args) { SpringApplication.run(CityApplication.class, args); //执行定时任务 QuartzUtil.addJob("每周更新推送数据JOB", "每周", "每周更新推送数据TRIGGER", "每周TRIGGER", PushJob.class, week); } }