学习springboot的旅程,就像蜗牛爬山,一点点的往上爬,一点点的欣赏旅途的风景
继续上一章的故事,小猿的经理又让小猿支持一下定时任务。此时的小猿望向远方的夕阳,呸,不对,是朝霞。嗯,小猿还是果断盖上电脑回家睡觉,等会再回来搞。。。。在熟睡中,小猿梦见一个和蔼的老人,左手拿着象棋子,右手拿着一本古朴的书籍。隐约见小猿瞄见了几个字《Quartz定时任务》
springboot 集成Quartz定时器
- 第一步:pom.xml
<!-- quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 第二步:在application.properties配置(基于数据库的方式)
## quartz
# 采用数据库存储方式
spring.quartz.job-store-type=jdbc
- 环境搞定了!
Quartz定时任务有两种方式实现
方式一:基于内存
- 第一步:创建定时业务类 继承【extends QuartzJobBean】
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.util.List;
import java.util.Map;
/**
* hxz定时测试类
*/
public class HxzJob extends QuartzJobBean {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private CoreServiceImpl coreService;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("我是定时任务");
}
}
- 第二步:通过配置类创建定时任务【@Configuration】:此步骤类似在xml配置Trigger和定时正则
import com.example.hxzboot.config.Quartz.Job.Hxz3Job;
import com.example.hxzboot.config.Quartz.Job.HxzJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 定时任务配置类
*/
@Configuration
public class QuartzConfig {
@Bean//创建定时业务类
public JobDetail testQuartz() {
return JobBuilder.newJob(HxzJob.class).withIdentity("Job111").storeDurably().build();
}
@Bean//创建Trigger定时任务及定时正则
public Trigger testQuartzTrigger2() {
//cron方式
return TriggerBuilder.newTrigger().forJob(testQuartz2())
.withIdentity("Job111")
.withSchedule(CronScheduleBuilder.cronSchedule("10 18 16 * * ?"))
.build();
}
}
方式二:基于数据库
- 第一步:数据库创建定时任务表,建表语句下载地址
- 第二步:创建定时业务类
//import com.example.hxzboot.Dome.Service.Core.impl.CoreServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
public class Hxz2Job implements Job {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
//@Autowired
//private CoreServiceImpl coreService;
private String parameter;
public void setParameter(String parameter) {
this.parameter = parameter;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("我是定时任务");
}
}
- 第三步:动态创建或删除定时任务(基于数据库)
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.annotations.GenericGenerator;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.rmi.CORBA.Util;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/quartz")
public class QuartzController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private Scheduler scheduler;
/**
* 创建定时任务
*/
@RequestMapping(value="/addjob",method = {RequestMethod.POST,RequestMethod.GET})
public void addjob()throws Exception{
//创建定时任务
try {
// 启动调度器
scheduler.start();
// 构建job信息
JobDetail jobDetail = JobBuilder.newJob(((Job)UtilClass.getClass("com.example.hxzboot.config.Quartz.Job.Hxz2Job")).getClass()).withIdentity("com.example.hxzboot.config.Quartz.Job.Hxz2Job").usingJobData("parameter", "你好啊").build();
// 表达式调度构建器(即任务执行的时间)
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("20 * * * * ?");
// 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("com.example.hxzboot.config.Quartz.Job.Hxz2Job").withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
} catch (SchedulerException e) {
throw new Exception("创建定时任务失败", e);
} catch (Exception e) {
throw new Exception("后台找不到该类名:" + "com.example.hxzboot.config.Quartz.Job.Hxz2Job", e);
}
}
/**
* 删除定时任务
*/
@RequestMapping(value="/deljob",method = {RequestMethod.POST,RequestMethod.GET})
public void deljob()throws Exception{
//创建定时任务
try {
try {
scheduler.pauseTrigger(TriggerKey.triggerKey("Job222"));
scheduler.unscheduleJob(TriggerKey.triggerKey("Job222"));
scheduler.deleteJob(JobKey.jobKey("Job222"));
} catch (Exception e) {
throw new Exception("删除定时任务失败");
}
} catch (SchedulerException e) {
throw new Exception("创建定时任务失败", e);
} catch (Exception e) {
throw new Exception("后台找不到该类名:" + "com.example.hxzboot.config.Quartz.Job.Hxz2Job", e);
}
}
}
class UtilClass{
public static Object getClass(String classname) throws Exception {
Class<?> class1 = Class.forName(classname);
return class1.newInstance();
}
}
梦完,小猿醒来,发现自己坐在电脑前了,双手搭在键盘上。而屏幕上显示的正是Quartz!!!