---
title: "现有web系统替换成Spring Boot2框架 之10 定时任务Quartz Scheduler"
author: "sanry"
date: "2019-02-22T11:25:24Z"
tags: []
categories: ["编程语言"]
slug: "web-spring-boot2-10-quartz-scheduler"
draft: false
lastmod: "2019-02-20T15:36:29Z"
id: 2437838
url: "https://sanry.iteye.com/blog/2437838"
---

## **10.1 pom.xml添加如下配置:**

 

&lt;!-- quartz定时任务 --&gt;

&lt;dependency&gt;

&lt;groupId&gt;org.quartz-scheduler&lt;/groupId&gt;

&lt;artifactId&gt;quartz&lt;/artifactId&gt;

&lt;/dependency&gt;

## **10.2 resources目录增加配置文件quartz.properties**

\# thread-pool

org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool

org.quartz.threadPool.threadCount=10

\# job-store

org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore

## **10.3 Quartz定时任务例子**

1. 数据库创建定时任务调度表

CREATE TABLE \`job\_config\` (

\`id\` INT(11) NOT NULL AUTO\_INCREMENT,

\`create\_time\` DATETIME DEFAULT NULL,

\`cron\_time\` VARCHAR(50) NOT NULL COMMENT '执行时间 例:0/8 * * * * ?',

\`full\_entity\` VARCHAR(255) NOT NULL COMMENT '任务类全路径',

\`group\_name\` VARCHAR(100) NULL COMMENT '任务组名称',

\`name\` VARCHAR(100) NOT NULL COMMENT '任务名',

\`status\` VARCHAR(2) NOT NULL COMMENT '任务状态，0-无效 1-有效',

\`update\_time\` DATETIME DEFAULT NULL,

\`remark\` VARCHAR(255) NOT NULL COMMENT '备注',

PRIMARY KEY (\`id\`),

UNIQUE KEY \`group\_name\` (\`group\_name\`,\`name\`)

)

DEFAULT CHARSET = utf8;

 

INSERT INTO \`job\_config\` (\`create\_time\`, \`cron\_time\`, \`full\_entity\`, \`group\_name\`, \`name\`, \`status\`, \`update\_time\`, \`remark\`) VALUES (now(), '0/7 * * * * ?', 'com.smallbss.quartz.CallEPCJob', 'instructions', 'call\_ecp', '1', now(),'定时发指令');

 

2. &lt;!--\[endif]--&gt;配置config启动定时任务

 

**QuartzConfig类：**

```
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

 

import org.quartz.impl.StdSchedulerFactory;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

 

import java.util.List;

 

@Configuration

public class QuartzConfig {

Logger logger = LoggerFactory.getLogger(getClass());

@Autowired

private ApplicationContext applicationContext;

 

@Autowired

private QuartzConfigService quartzConfigService;

 

@Bean

public StdSchedulerFactory stdSchedulerFactory() {

StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();

// 获取JobConfig集合

List<QuartzBean> quartzList = quartzConfigService.findAllByStatus(1);

logger.debug("Setting the Scheduler up");

for (QuartzBean quartz : quartzList) {

try {

Boolean flag = SchedulerUtil.createScheduler(quartz, applicationContext);

logger.info("quartz job " + quartz.getName() + " Path:" + quartz.getFullEntity() + " start... 执行结果："

+ flag);

} catch (Exception e) {

e.printStackTrace();

}

}

return stdSchedulerFactory;

}

}
```

 

 

**SchedulerUtil 类：**

 

```
import org.quartz.*;

import org.quartz.impl.StdSchedulerFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.core.io.ClassPathResource;

import org.springframework.scheduling.quartz.CronTriggerFactoryBean;

import org.springframework.scheduling.quartz.JobDetailFactoryBean;

import org.springframework.scheduling.quartz.SchedulerFactoryBean;

 

import java.text.ParseException;

 

public class SchedulerUtil {

 

// 定时任务Scheduler的工厂类，Quartz提供

private static StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();

// CronTrigger的工厂类

private static CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();

// JobDetail的工厂类

private static JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();

// 自动注入Spring Bean的工厂类

private static AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory();

// 定时任务Scheduler的工厂类，Spring Framework提供

private static SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();

 

static {

// 加载指定路径的配置

schedulerFactoryBean.setConfigLocation(new ClassPathResource("quartz.properties"));

}

 

/**

 * 创建定时任务，根据参数，创建对应的定时任务，并使之生效

 *

 * @param config

 * @param context

 * @return

 */

public static boolean createScheduler(QuartzBean config, ApplicationContext context) {

try {

// 创建新的定时任务

return create(config, context);

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

 

/**

 * 删除旧的定时任务，创建新的定时任务

 *

 * @param oldConfig

 * @param config

 * @param context

 * @return

 */

public static Boolean modifyScheduler(QuartzBean oldConfig, QuartzBean config, ApplicationContext context) {

if (oldConfig == null || config == null || context == null) {

return false;

}

try {

String oldJobClassStr = oldConfig.getFullEntity();

String oldName = oldJobClassStr + oldConfig.getId();

String oldGroupName = oldConfig.getGroupName();

// 1、清除旧的定时任务

delete(oldName, oldGroupName);

// 2、创建新的定时任务

return create(config, context);

} catch (SchedulerException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

 

/**

 * 提取的删除任务的方法

 *

 * @param oldName

 * @param oldGroupName

 * @return

 * @throws SchedulerException

 */

private static Boolean delete(String oldName, String oldGroupName) throws SchedulerException {

TriggerKey key = new TriggerKey(oldName, oldGroupName);

Scheduler oldScheduler = schedulerFactory.getScheduler();

// 根据TriggerKey获取trigger是否存在，如果存在则根据key进行删除操作

Trigger keyTrigger = oldScheduler.getTrigger(key);

if (keyTrigger != null) {

oldScheduler.unscheduleJob(key);

}

return true;

}

 

/**

 * 提取出的创建定时任务的方法

 *

 * @param config

 * @param context

 * @return

 */

private static Boolean create(QuartzBean config, ApplicationContext context) {

try {

// 创建新的定时任务

String jobClassStr = config.getFullEntity();

Class clazz = Class.forName(jobClassStr);

String name = jobClassStr + config.getId();

String groupName = config.getGroupName();

String description = config.toString();

String time = config.getCronTime();

 

JobDetail jobDetail = createJobDetail(clazz, name, groupName, description);

if (jobDetail == null) {

return false;

}

Trigger trigger = createCronTrigger(jobDetail, time, name, groupName, description);

if (trigger == null) {

return false;

}

 

jobFactory.setApplicationContext(context);

 

schedulerFactoryBean.setJobFactory(jobFactory);

schedulerFactoryBean.setJobDetails(jobDetail);

schedulerFactoryBean.setTriggers(trigger);

schedulerFactoryBean.afterPropertiesSet();

Scheduler scheduler = schedulerFactoryBean.getScheduler();

if (!scheduler.isShutdown()) {

scheduler.start();

}

return true;

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SchedulerException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

 

/**

 * 根据指定的参数，创建JobDetail

 *

 * @param clazz

 * @param name

 * @param groupName

 * @param description

 * @return

 */

public static JobDetail createJobDetail(Class clazz, String name, String groupName, String description) {

jobDetailFactory.setJobClass(clazz);

jobDetailFactory.setName(name);

jobDetailFactory.setGroup(groupName);

jobDetailFactory.setDescription(description);

jobDetailFactory.setDurability(true);

jobDetailFactory.afterPropertiesSet();

return jobDetailFactory.getObject();

}

 

/**

 * 根据参数，创建对应的CronTrigger对象

 *

 * @param job

 * @param time

 * @param name

 * @param groupName

 * @param description

 * @return

 */

public static CronTrigger createCronTrigger(JobDetail job, String time, String name, String groupName,

String description) {

factoryBean.setName(name);

factoryBean.setJobDetail(job);

factoryBean.setCronExpression(time);

factoryBean.setDescription(description);

factoryBean.setGroup(groupName);

try {

factoryBean.afterPropertiesSet();

} catch (ParseException e) {

e.printStackTrace();

}

return factoryBean.getObject();

}

}
```

 

 

**AutoWiringSpringBeanJobFactory类：**

 

```
import org.quartz.spi.TriggerFiredBundle;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.scheduling.quartz.SpringBeanJobFactory;

 

public final class AutoWiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

 

private transient AutowireCapableBeanFactory beanFactory;

 

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

beanFactory = applicationContext.getAutowireCapableBeanFactory();

}

 

@Override

protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {

 

final Object job = super.createJobInstance(bundle);

beanFactory.autowireBean(job);

return job;

}

 

}
```

 

 

**QuartzBean 类**

```
import java.util.Date;

 

public class QuartzBean {

private Integer id;

private String name;

private String fullEntity;

private String groupName;

private String cronTime;

private String status;

private Date createTime;

private Date updateTime;

 

public Integer getId() {

return id;

}

 

public void setId(Integer id) {

this.id = id;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public String getFullEntity() {

return fullEntity;

}

 

public void setFullEntity(String fullEntity) {

this.fullEntity = fullEntity;

}

 

public String getGroupName() {

return groupName;

}

 

public void setGroupName(String groupName) {

this.groupName = groupName;

}

 

public String getCronTime() {

return cronTime;

}

 

public void setCronTime(String cronTime) {

this.cronTime = cronTime;

}

 

public String getStatus() {

return status;

}

 

public void setStatus(String status) {

this.status = status;

}

 

public Date getCreateTime() {

return createTime;

}

 

public void setCreateTime(Date createTime) {

this.createTime = createTime;

}

 

public Date getUpdateTime() {

return updateTime;

}

 

public void setUpdateTime(Date updateTime) {

this.updateTime = updateTime;

}

}
```

 

 

**QuartzConfigService 类：**

 

```
import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class QuartzConfigService {

@Autowired

private CommonService cs;

public List<QuartzBean> findAllByStatus(Integer status) {

String sql = "select * from job_config where status='1'";

return MapToJobConfigList(cs.queryBySql(sql));

}


public List<QuartzBean> MapToJobConfigList(List<Map<String, Object>> list) {

List<QuartzBean> jobList = new ArrayList<QuartzBean>();

QuartzBean quartzBean  = null;

for (Map<String, Object> map : list) {

quartzBean = new QuartzBean();

quartzBean.setId((Integer) map.get("id"));

quartzBean.setCreateTime((Date) map.get("create_time"));

quartzBean.setCronTime((String) map.get("cron_time"));

quartzBean.setFullEntity((String) map.get("full_entity"));

quartzBean.setGroupName((String) map.get("group_name"));

quartzBean.setName((String) map.get("name"));

quartzBean.setStatus((String) map.get("status"));

quartzBean.setUpdateTime((Date) map.get("update_time"));

jobList.add(quartzBean);

}

return jobList;

}

}
```

 

 

**CallEPCJob 类：**

 

```
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class CallEPCJob implements Job {

@Autowired
private Logger logger=LoggerFactory.getLogger(CallEPCJob.class);

public void execute(JobExecutionContext context) {

logger.info("-----CallEPCJob--------");

}

}
```