springboot2.0整合quartz(任务的增删改查、暂停、恢复)QuartzConfiguration配置类
package com.fig;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.fig.AutowireCapableBeanFactory;
import t.ApplicationContext;
import t.ApplicationContextAware;
import t.annotation.Bean;
import t.annotation.Configuration;
import io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import javax.sql.DataSource;
import java.io.IOException;
/**
* quartz定时任务配置
*/
@Configuration
@EnableScheduling
public class QuartzConfiguration {
/**
* 继承org.springframework.scheduling.quartz.SpringBeanJobFactory
* 实现任务实例化⽅式
*/
public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
@Override
public void setApplicationContext(final ApplicationContext context) {
beanFactory = AutowireCapableBeanFactory();
}
/**
* 将job实例交给spring ioc托管
* 我们在job实例实现类内可以直接使⽤spring注⼊的调⽤被spring ioc管理的实例
*
jfinal增删改查* @param bundle
* @return
* @throws Exception
*/
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = ateJobInstance(bundle);
/**
* 将job实例交付给spring ioc
*/
beanFactory.autowireBean(job);
return job;
return job;
}
}
/**
* 配置任务⼯⼚实例
*
* @param applicationContext spring上下⽂实例
* @return
*/
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
/**
* 采⽤⾃定义任务⼯⼚整合spring实例来完成构建任务
* see {@link AutowiringSpringBeanJobFactory}
*/
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
/**
* 配置任务调度器
* 使⽤项⽬数据源作为quartz数据源
*
* @param jobFactory ⾃定义配置任务⼯⼚
* @param dataSource 数据源实例
* @return
* @throws Exception
*/
@Bean(destroyMethod = "destroy", autowire = Autowire.NO)//可以配置多数据源模式
public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) throws Exception {        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
//将spring管理job⾃定义⼯⼚交由调度器维护
schedulerFactoryBean.setJobFactory(jobFactory);
//设置覆盖已存在的任务
schedulerFactoryBean.setOverwriteExistingJobs(true);
//项⽬启动完成后,等待2秒后开始执⾏调度器初始化
schedulerFactoryBean.setStartupDelay(2);
//设置调度器⾃动运⾏
schedulerFactoryBean.setAutoStartup(true);
//设置数据源,使⽤与项⽬统⼀数据源
schedulerFactoryBean.setDataSource(dataSource);
//设置上下⽂spring bean name
schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContext");
//设置配置⽂件位置
schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
return schedulerFactoryBean;
}
}
quartz.properties
#调度器实例名称
org.quartz.scheduler.instanceName = quartzScheduler12
#调度器实例编号⾃动⽣成
org.quartz.scheduler.instanceId = AUTO
#持久化⽅式配置
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
#持久化⽅式配置数据驱动,MySQL数据库
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#quartz相关数据表前缀名
org.quartz.jobStore.tablePrefix = QRTZ_
#开启分布式部署
org.quartz.jobStore.isClustered = true
#配置是否使⽤
org.quartz.jobStore.useProperties = false
#分布式节点有效性检查时间间隔,单位:毫秒
org.quartz.jobStore.clusterCheckinInterval = 20000
#线程池实现类
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
#执⾏最⼤并发线程数量
org.quartz.threadPool.threadCount = 10
#线程优先级
org.quartz.threadPool.threadPriority = 5
#配置为守护线程,设置后任务将不会执⾏
#org.quartz.threadPool.makeThreadsDaemons=true
#配置是否启动⾃动加载数据库内的定时任务,默认true
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true Quartzjob类:⾃定义任务记录实体,对应数据库的quartzjob表
package com.ity;
import batisplus.annotation.IdType;
import batisplus.annotation.TableId;
import batisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
perimental.Accessors;
/**
* <p>
*
* </p>
*
* @author testjava
* @since 2020-07-11
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@Accessors(chain = true)
@ApiModel(value="Quartzjob对象", description="")
public class Quartzjob implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "任务id")
@TableId(value = "jobId", type = IdType.AUTO)
private Integer jobId;
@ApiModelProperty(value = "任务名称")
@TableField("jobName")
private String jobName;
@ApiModelProperty(value = "任务分组")
@TableField("jobGroup")
private String jobGroup;
@ApiModelProperty(value = "任务描述")
private String description;
@ApiModelProperty(value = "执⾏类")
@TableField("jobClassName")
private String jobClassName;
@ApiModelProperty(value = "执⾏时间表达式")
@TableField("cronExpression")
private String cronExpression;
@ApiModelProperty(value = "触发器名称")
@TableField("triggerName")
private String triggerName;
@ApiModelProperty(value = "触发器状态")
@TableField("triggerState")
private String triggerState;
@ApiModelProperty(value = "任务名称⽤于修改")
@TableField("oldJobName")
private String oldJobName;
@ApiModelProperty(value = "任务分组⽤于修改")
@TableField("oldJobGroup")
private String oldJobGroup;
}
在service层实现:
⽤的mybatisplus实现任务的增删改查、暂停、恢复操作package com.atguigu.springbooquartz.service.impl;
import com.atguigu.springbooquartzmon.Result;
import com.ity.Quartzjob;
import com.atguigu.springbooquartz.mapper.QuartzjobMapper;
import com.atguigu.springbooquartz.service.QuartzjobService;
import ditions.query.QueryWrapper; import apper.BaseMapper;
import sion.plugins.pagination.Page; import sion.service.impl.ServiceImpl; import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
*  服务实现类
* </p>
*
* @author testjava
* @since 2020-07-11
*/
@Service
public class QuartzjobServiceImpl extends ServiceImpl<QuartzjobMapper, Quartzjob> implements QuartzjobService {
@Qualifier("schedulerFactoryBean")
@Autowired
private Scheduler scheduler;
@Autowired
private BaseMapper baseMapper;
@Override
public Page listQuartzJob(String jobName, Integer pageNum, Integer pageSize) {
Page<Quartzjob> page=new Page<>(pageNum,pageSize);
QueryWrapper<Quartzjob> queryWrapper=new QueryWrapper();
queryWrapper.eq("jobName",jobName);
baseMapper.selectPage(page,queryWrapper);
return page;
}
@Override
public Result saveJob(Quartzjob quartz){
try {
//如果是修改展⽰旧的任务
OldJobGroup() != null && !"".OldJobGroup())){
JobKey key = new OldJobName(),OldJobGroup());
scheduler.deleteJob(key);
}
baseMapper.insert(quartz);
//构建job信息
Class cls = Class.JobClassName()) ;
JobDetail job = wJob(cls).JobName(),
.Description()).build();
// 触发时间点
CronScheduleBuilder cronScheduleBuilder = CronExpression().trim());            Trigger trigger = wTrigger().withIdentity("trigger"+JobName(), JobGroup())
.startNow().withSchedule(cronScheduleBuilder).build();
//交由Scheduler安排触发
scheduler.scheduleJob(job, trigger);
} catch (Exception e) {
e.printStackTrace();
();
}
return Result.ok();
}
@Override
public Result triggerJob(String jobName, String jobGroup) {
JobKey key = new JobKey(jobName,jobGroup);
try {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。