整理一下很久之前写的quartz集成到spring boot代码,主要为了实现可视化操作定时任务,只添加了后台rest接口和代码,前台代码请自行处理。
1. 引入quartz
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
<exclusions>
<exclusion>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</exclusion>
</exclusions>
</dependency>
2. quartz sql脚本:可以从quartz官网上根据database选择下载
http://www.quartz-scheduler.org/downloads/
另外,需要自定义定时任务表和定时任务执行日志表:
-- ----------------------------
-- 定时任务表
-- ----------------------------
DROP TABLE IF EXISTS `schedule_job`;
CREATE TABLE `schedule_job` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '任务id',
`bean_name` varchar(200) NOT NULL COMMENT 'spring bean名称',
`method_name` varchar(100) NOT NULL COMMENT '方法名',
`params` varchar(2000) DEFAULT NULL COMMENT '参数',
`cron_expression` varchar(100) NOT NULL COMMENT 'cron表达式',
`status` int DEFAULT NULL COMMENT '任务状态 0:正常 1:暂停',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
`crt_time` datetime DEFAULT NULL,
`crt_user` varchar(50) DEFAULT NULL,
`crt_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='定时任务表';
-- ----------------------------
-- 定时任务日志表
-- ----------------------------
DROP TABLE IF EXISTS `schedule_job_log`;
CREATE TABLE `schedule_job_log` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '任务日志id',
`job_id` int(11) NOT NULL COMMENT '任务id',
`bean_name` varchar(200) NOT NULL COMMENT 'spring bean名称',
`method_name` varchar(100) NOT NULL COMMENT '方法名',
`params` varchar(2000) DEFAULT NULL COMMENT '参数',
`status` int NOT NULL COMMENT '任务状态 0:成功 1:失败',
`error` varchar(2000) DEFAULT NULL COMMENT '失败信息',
`times` int(11) NOT NULL COMMENT '耗时(单位:毫秒)',
`crt_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `job_id` (`job_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='定时任务日志表';
3. 配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
public class SchedulerConfiguration {
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource);
//quartz参数
Properties prop = new Properties();
prop.put("org.quartz.scheduler.instanceName", "TestScheduler");
prop.put("org.quartz.scheduler.instanceId", "AUTO");
//线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
//JobStore配置
prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
//集群配置
prop.put("org.quartz.jobStore.isClustered", "false");
//prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
//prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
prop.put("org.quartz.jobStore.misfireThreshold", "12000");
prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
factory.setQuartzProperties(prop);
factory.setSchedulerName("TestScheduler");
//延时启动
factory.setStartupDelay(30);
factory.setApplicationContextSchedulerContextKey("applicationContextKey");
//可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
factory.setOverwriteExistingJobs(true);
//设置自动启动,默认为true
factory.setAutoStartup(true);
return factory;
}
}
以新增定时任务为例,大体流程如下:
4. Controller接口
/**
* 定时任务
*
*/
@Controller
@RequestMapping("job")
@Api("定时任务模块")
public class ScheduleJobController {
@Autowired
private ScheduleJobBiz biz;
/**
* 查询列表
*
* @param params
* @return
*/
@RequestMapping(value = "/page",method = RequestMethod.GET)
@ResponseBody
public TableResultResponse list(@RequestParam Map<String, Object> params){
Query query = new Query(params);
return biz.selectByQuery(query);
}
/**
* 新增定时任务
*
* @param scheduleJob
* @return
*/
@RequestMapping(value = "",method = RequestMethod.POST)
@ResponseBody
public ObjectRestResponse add(@RequestBody ScheduleJob scheduleJob){
return biz.add(scheduleJob);
}
/**
* 修改定时任务
*
* @param id
* @param scheduleJob
* @return
*/
@RequestMapping(value = "/{id}",method = RequestMethod.PUT)
@ResponseBody
public ObjectRestResponse update(@PathVariable int id, @RequestBody ScheduleJob scheduleJob){
return biz.update(id, scheduleJob);
}
/**
* 批量删除
*
* @param ids
* @return
*/
@RequestMapping(value = "/batchDel",method = RequestMethod.DELETE)
@ResponseBody
public ObjectRestResponse delete(@RequestBody List<Integer> ids){
return biz.deleteBatch(ids);
}
/**
* 立即执行任务
*
* @param ids
* @return
*/
@RequestMapping(value = "/run",method = RequestMethod