quartz 学习教程「终于解决」

quartz 学习教程「终于解决」今天闲来无事把前几天去的分享一下在一个项目中要求是页面可以自定义动态定时任务 所以 我就以quartz实现的​ quartz 分为三个组件1.

欢迎大家来到IT世界,在知识的湖畔探索吧!

今天闲来无事把前几天去的分享一下

在一个项目中要求是页面可以自定义动态定时任务 所以 我就以quartz实现的

​ quartz 分为三个组件

1. 任务组件 jobDetail

我们想要完成任务

2. 触发器 Trigger

执行任务的条件 simpleTrigger 和crontigger

3.调度器Scheduler

![Untitled1](C:\Users\Administrator\Desktop\Untitled1.png)

例子:

配置文件导入

“`

<!– https://mvnrepository.com/artifact/org.quartz-scheduler/quartz –>

<dependency>

<groupId>org.quartz-scheduler</groupId>

<artifactId>quartz</artifactId>

<version>2.3.2</version>

</dependency>

<!– https://mvnrepository.com/artifact/org.quartz-scheduler/quartz-jobs –>

<dependency>

<groupId>org.quartz-scheduler</groupId>

<artifactId>quartz-jobs</artifactId>

<version>2.3.2</version>

</dependency>

“`

“`java

import java.util.HashMap;

import java.util.Map;

import org.quartz.JobBuilder;

import org.quartz.JobDataMap;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SimpleScheduleBuilder;

import org.quartz.SimpleTrigger;

import org.quartz.Trigger;

import org.quartz.TriggerBuilder;

import org.quartz.impl.StdSchedulerFactory;

import cn.test.quartz.job.helloJob;

public class HelloSchedulerDemo {

public static void main(String[] args) throws Exception{

JobDataMap jobDataMap=new JobDataMap();

jobDataMap.put(“sdfs”, “0”);

//调度器

Scheduler defaultScheduler = StdSchedulerFactory.getDefaultScheduler();

//任务实例

JobDetail newJob = JobBuilder.newJob(helloJob.class)

.usingJobData(jobDataMap) //可以给任务传输数据 jobDataMap 类型 和map差不多

.withIdentity(“hellojob”, “group1”).build();

//可以获取一些任务属性

System.out.println(newJob.getJobBuilder());

System.out.println(newJob.getKey());

System.out.println(newJob.getKey().getGroup());

System.out.println(newJob.getKey().getName());

//触发器

Trigger trigger = TriggerBuilder.newTrigger()

.withIdentity(“trigger1”, “triggergroup1”)

.startNow()//现在开始

.usingJobData(jobDataMap) //可以给任务传输数据 jobDataMap 类型 和map差不多

.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5)) //可以从数据库获取

.build();

//调度器关联触发器 保证触发器执行任务

defaultScheduler.scheduleJob(newJob,trigger);

defaultScheduler.start(); //开始

//defaultScheduler.shutdown();//停止

//defaultScheduler.pauseAll();//暂停

}

}

“`

调取的任务

“`java

import java.time.LocalDateTime;

import org.quartz.Job;

import org.quartz.JobDataMap;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.quartz.PersistJobDataAfterExecution;

@PersistJobDataAfterExecution //多次调用job都会对JobDataMap进行持久化

public class helloJob implements Job{

private String massage;

public void setMassage(String massage) {

this.massage = massage;

}

//job通过JobExecutionContext获取 可以获取运行时环境以及job的明细数据

@Override

public void execute(JobExecutionContext context) throws JobExecutionException {

// TODO Auto-generated method stub

System.out.println(context.getJobDetail().getKey().getName());//得到任务调度数据

System.out.println(context.getJobDetail().getJobClass().getName());

System.out.println(context.getTrigger().getKey().getName());//得到触发器的数据

System.out.println(context.getFireTime());//获取当期任务执行时间

System.out.println(context.getNextFireTime());//获取下一次执行任务时间

JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); //获取任务调度的数据

System.out.println(jobDataMap.get(“massage”));//获取任务调度的参数值

JobDataMap jobDataMap2 = context.getTrigger().getJobDataMap();//获取触发器获取的数据

System.out.println(jobDataMap2.get(“massage”));

System.out.println(massage); //jobdatamap 默认调用执行器的set方法 所以有相同名字的参数先显示tigger 然后再jobdetail的值

}

}

“`

job通过JobExecutionContext获取 可以获取运行时环境以及job的明细数据

“`Java

context.getJobDetail().getKey().getName() //获取任务组名称

context.getJobDetail().getJobClass().getName() //获取任务组类的名称(带路径)

“`

有状态和无状态任务信息意思是 JobDataMap 每次是否都重新初始化 每次都初始化的叫无状态任务信息 而每次都不初始化叫有状态任务信息“@PersistJobDataAfterExecution“ 可以使无状态任务信息转化成有任务状态信息

设置开始时间和结束时间

“`java

Trigger trigger = TriggerBuilder.newTrigger()

.withIdentity(“trigger1”, “triggergroup1”)

.startAt(new Date())//开始时间

.endAt(new Date())//结束时间

.usingJobData(jobDataMap) //可以给任务传输数据 jobDataMap 类型 和map差不多

.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5)) //每五秒在开始时间和结束时间之内执行 可以从数据库获取

.build();

//获取开始时间结束时间

public class helloJob implements Job{

@Override

public void execute(JobExecutionContext context) throws JobExecutionException {

System.out.println(context.getTrigger().getStartTime());

System.out.println(context.getTrigger().getEndTime());

}

}

“`

隔一段时间重复执行并设置执行次数withRepeatCount **从零开始**

“`Java

.withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5).withRepeatCount(3))

“`

结束时间的权限大于次数

# cronExpression表达式符号解释

| 字段 | 允许值 | 允许的特殊字符 |

| —- | ——————— | ————– |

| 秒 | 0-59 | – * / |

| 分 | 0-59 | – * / |

| 小时 | 0-23 | – * / |

| 日期 | 1-31 | – * ? / L W C |

| 月份 | 1-12 或者 JAN-DEC | – * / |

| 星期 | 1-7 或者 SUN-SAT | – * ? / L C # |

| 年 | (可选)留空1970-2099 | – * / |

* :表示所有值. 例如:在分的字段上设置 “*”,表示每一分钟都会触发。

? :表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为”?” 具体设置为 0 0 0 10 * ?

– :表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。

, :表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发

/ :用于递增触发。如在秒上面设置”5/15″ 表示从5秒开始,每增15秒触发(5,20,35,50)。 在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。

L :表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7″或”SAT”。如果在”L”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6L”这样的格式,则表示“本月最后一个星期五”。

W :表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上设置”15W”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”W”前只能设置具体的数字,不允许区间”-“)。’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发。

\#:序号(表示每月的第几周星期几),例如在周字段上设置”6#3″表示在每月的第三个周星期六.注意如果指定”6#5″,正好第五周没有星期六,则不会触发该配置(用在母亲节和父亲节再合适不过了)周字段的设置,若使用英文字母是不区分大小写的 MON 与mon相同.

表达式示例:

格式: \[秒\]\[分\]\[小时\]\[日\]\[月\]\[周\]\[年\]

这是cron表达式例子

“`

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import org.quartz.CalendarIntervalScheduleBuilder;

import org.quartz.CronScheduleBuilder;

import org.quartz.JobBuilder;

import org.quartz.JobDataMap;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SimpleScheduleBuilder;

import org.quartz.SimpleTrigger;

import org.quartz.Trigger;

import org.quartz.TriggerBuilder;

import org.quartz.impl.StdSchedulerFactory;

import cn.test.quartz.job.helloJob;

public class HelloSchedulerDemo {

public static void main(String[] args) throws Exception{

JobDataMap jobDataMap=new JobDataMap();

jobDataMap.put(“sdfs”, “0”);

//调度器

Scheduler defaultScheduler = StdSchedulerFactory.getDefaultScheduler();

//任务实例

JobDetail newJob = JobBuilder.newJob(helloJob.class)

.usingJobData(jobDataMap) //可以给任务传输数据 jobDataMap 类型 和map差不多

.withIdentity(“hellojob”, “group1”).build();

//可以获取一些任务属性

System.out.println(newJob.getJobBuilder());

System.out.println(newJob.getKey());

System.out.println(newJob.getKey().getGroup());

System.out.println(newJob.getKey().getName());

//触发器

Trigger trigger = TriggerBuilder.newTrigger()

.withIdentity(“trigger1”, “triggergroup1”)

.usingJobData(jobDataMap) //可以给任务传输数据 jobDataMap 类型 和map差不多

.withSchedule(CronScheduleBuilder.cronSchedule(“0/1 * * * * ?”)) //每五秒在开始时间和结束时间之内执行 可以从数据库获取

.build();

//调度器关联触发器 保证触发器执行任务

defaultScheduler.scheduleJob(newJob,trigger);

defaultScheduler.start(); //开始

//defaultScheduler.shutdown();//停止

//defaultScheduler.pauseAll();//暂停

defaultScheduler.standby();挂起

defaultScheduler.shutdown(true);关闭 里面的true是表示所有正在执行的job执行完成后再关闭 false表示立即关闭

}

}

“`

quartz.propreties

“`properties

# Default Properties file for use by StdSchedulerFactory

# to create a Quartz Scheduler Instance, if a different

# properties file is not explicitly specified.

#

org.quartz.scheduler.instanceName: DefaultQuartzScheduler (表示调度器的名字)

#org.quartz.scheduler.instanceid auto 表示调度器id 在集群使用(这个是我自己添加的 这里没有只是注意一下 auto 是quartz自动生成)

org.quartz.scheduler.rmi.export: false

org.quartz.scheduler.rmi.proxy: false

org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool(线程池的接口类)

org.quartz.threadPool.threadCount: 10 (最少是1小于100 线程池大小)

org.quartz.threadPool.threadPriority: 5 (线程执行优先级就是越小越优先执行)

org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

“`

监听器 主要三种 jobListener 、triggerListener、SchedulerListener

一、jobListener

​ 里面的方法有四个

– getName()获取jobListener名称

– jobToBeExecuted() 就是Scheduler执行job时调用

– jobExecutionVetoed() 是Scheduler将要执行job时调用 但又被triggerListener否决时调用

– jobWasExecuted() 就是Scheduler执行job时调用后 执行这个任务

添加jobListener

“`Java

StdSchedulerFactory.getDefaultScheduler().getListenerManager().addJobListener(自定义实现JobListener的类,EverythingMatcher.allJobs());

“`

“`Java

EverythingMatcher.allJobs() //是代表全局就是所有的都监听

“`

“`Java

StdSchedulerFactory.getDefaultScheduler().getListenerManager().addJobListener(自定义实现JobListener的类,KeyMatcher.keyEquals(JobKey.jobKey(“jobDeatil的name”, “jobDeatil的group”)));//这是局部 这是监听某个jobDeatil

“`

这是jobLister 要实现的功能

“`

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.quartz.JobListener;

import org.quartz.ScheduleBuilder;

public class MyJobListener implements JobListener{

@Override

public String getName() {

String simpleName = this.getClass().getSimpleName();

System.out.println(“监听器的名称:”+simpleName);

return null;

}

@Override

public void jobToBeExecuted(JobExecutionContext context) {

// TODO Auto-generated method stub

String name = context.getJobDetail().getKey().getName();

System.out.println(“job的名称是”+name);

System.out.println(“Schedule 调用jobDetail时执行的方法”);

}

@Override

public void jobExecutionVetoed(JobExecutionContext context) {

// TODO Auto-generated method stub

System.out.println(“Scheduler将要执行job时调用 但又被triggerListener否决时调用”);

}

@Override

public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {

// TODO Auto-generated method stub

System.out.println(“cheduler执行job时调用后 执行这个任务”);

}

}

“`

二、triggerListener

里面有五个方法

– getName() 用于获取触发器的名字

– triggerFired() 当与监听器相关联的tigger被触发 job上的execute()方法将被执行 Scheduler就调用该方法

– vetoJobExecution() 在tigger触发后,job将要被执行时由Scheduler调用这个方法triggerListener 给了一个选择去否定job的执行,例如这个方法返回true 这个job将不会为此次tigger触发而得到执行

– triggerMisfired() 当Scheduler调用tigger错过触发时 你应该关注此方法中持续时间长的逻辑在出现错过tigger时 长逻辑会导致骨牌效应 所以应当保持这上方法尽量小

– triggerComplete() 当Scheduler调用tigger触发完成job时调用的

列子

“`

import org.quartz.JobExecutionContext;

import org.quartz.Trigger;

import org.quartz.Trigger.CompletedExecutionInstruction;

import org.quartz.TriggerListener;

public class MyTriggerListener implements TriggerListener{

@Override

public String getName() {

System.out.println(this.getClass().getName()); //得到触发器名称

return this.getClass().getName(); 这个必须返回去

}

@Override

public void triggerFired(Trigger trigger, JobExecutionContext context) {

System.out.println(“当触发器触发时候执行”);

// TODO Auto-generated method stub

}

@Override

public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {

// TODO Auto-generated method stub

return true;//这个方法返回true 这个job将不会为此次tigger触发而得到执行

}

@Override

public void triggerMisfired(Trigger trigger) {

// TODO Auto-generated method stub

System.out.println(“错过触发”);

}

@Override

public void triggerComplete(Trigger trigger, JobExecutionContext context,

CompletedExecutionInstruction triggerInstructionCode) {

// TODO Auto-generated method stub

System.out.println(“当调用完成时触发”);

}

}

“`

“`

StdSchedulerFactory.getDefaultScheduler().getListenerManager().addTriggerListener(自定义实现TriggerListener的类,EverythingMatcher.allJobs()); 全局监听

“`

“`

StdSchedulerFactory.getDefaultScheduler().getListenerManager().addTriggerListener(自定义实现JobListener的类,KeyMatcher.keyEquals(JobKey.jobKey(“tigger的name”, “tigger的group”))); 局部监听

“`

三、SchedulerListener

– jobScheduled()Scheduler 在有新的 JobDetail 部署时调用此方法。

– jobUnscheduled()Scheduler 在有新的 JobDetail卸载时调用此方法

– triggerFinalized() 当一个 Trigger 来到了再也不会触发的状态时调用这个方法。除非这个 Job 已设置成了 持久性,否则它就会从 Scheduler 中移除。

– triggersPaused()Scheduler 调用这个方法是发生在一个 Trigger 或 Trigger 组被暂停时。假如是 Trigger 组的话,triggerName 参数将为 null。

– triggersResumed()Scheduler 调用这个方法是发生成一个 Trigger 或 Trigger 组从暂停中恢复时。假如是 Trigger 组的话,triggerName 参数将为 null。

– jobsPaused()当一个或一组 JobDetail 暂停时调用这个方法。

– jobsResumed()当一个或一组 Job 从暂停上恢复时调用这个方法。假如是一个 Job 组,jobName 参数将为 null。

– schedulerError()Scheduler 的正常运行期间产生一个严重错误时调用这个方法。错误的类型会各式的,但是下面列举了一些错误例子:初始化 Job 类的问题,试图去找到下一 Trigger 的问题,JobStore 中重复的问题,数据存储连接的问题。我们可以使用 SchedulerException 的 getErrorCode() 或者 getUnderlyingException() 方法或获取到特定错误的更详尽的信息。

– schedulerShutdown()Scheduler 调用这个方法用来通知 SchedulerListener Scheduler 将要被关闭。

有些没有列出来的如下

“`Java

import org.quartz.JobDetail;

import org.quartz.SchedulerException;

import org.quartz.SchedulerListener;

import org.quartz.Trigger;

public class MySchedulerListener implements SchedulerListener {

@Override

public void jobScheduled(Trigger trigger) {

System.out.println(“任务被部署时被执行”);

}

@Override

public void triggerFinalized(Trigger trigger) {

System.out.println(“任务完成了它的使命,光荣退休时被执行”);

}

@Override

public void jobAdded(JobDetail jobDetail) {

System.out.println(“一个新的任务被动态添加时执行”);

}

@Override

public void jobUnscheduled(String triggerName, String triggerGroup) {

System.out.println(“任务被卸载时被执行”);

}

@Override

public void triggersPaused(String triggerName, String triggerGroup) {

System.out.println(triggerGroup + “所在组的全部触发器被停止时被执行”);

}

@Override

public void triggersResumed(String triggerName, String triggerGroup) {

System.out.println(triggerGroup + “所在组的全部触发器被回复时被执行”);

}

@Override

public void jobDeleted(String jobName, String groupName) {

System.out.println(groupName + “.” + jobName + “被删除时被执行”);

}

@Override

public void jobsPaused(String jobName, String jobGroup) {

System.out.println(jobGroup + “(一组任务)被暂停时被执行”);

}

@Override

public void jobsResumed(String jobName, String jobGroup) {

System.out.println(jobGroup + “(一组任务)被回复时被执行”);

}

@Override

public void schedulerError(String msg, SchedulerException cause) {

System.out.println(“出现异常” + msg + “时被执行”);

cause.printStackTrace();

}

@Override

public void schedulerInStandbyMode() {

System.out.println(“scheduler被设为standBy等候模式时被执行”);

}

@Override

public void schedulerStarted() {

System.out.println(“scheduler启动时被执行”);

}

@Override

public void schedulerShutdown() {

System.out.println(“scheduler关闭时被执行”);

}

@Override

public void schedulerShuttingdown() {

System.out.println(“scheduler正在关闭时被执行”);

}

}

“`

其实换很多 其余的可以自行了解

“`

import org.quartz.JobDetail;

import org.quartz.JobKey;

import org.quartz.SchedulerException;

import org.quartz.SchedulerListener;

import org.quartz.Trigger;

import org.quartz.TriggerKey;

public class MySchedulerListener implements SchedulerListener{

@Override

public void jobScheduled(Trigger trigger) {

// TODO Auto-generated method stub

}

@Override

public void jobUnscheduled(TriggerKey triggerKey) {

// TODO Auto-generated method stub

}

@Override

public void triggerFinalized(Trigger trigger) {

// TODO Auto-generated method stub

}

@Override

public void triggerPaused(TriggerKey triggerKey) {

// TODO Auto-generated method stub

}

@Override

public void triggersPaused(String triggerGroup) {

// TODO Auto-generated method stub

}

@Override

public void triggerResumed(TriggerKey triggerKey) {

// TODO Auto-generated method stub

}

@Override

public void triggersResumed(String triggerGroup) {

// TODO Auto-generated method stub

}

@Override

public void jobAdded(JobDetail jobDetail) {

// TODO Auto-generated method stub

}

@Override

public void jobDeleted(JobKey jobKey) {

// TODO Auto-generated method stub

}

@Override

public void jobPaused(JobKey jobKey) {

// TODO Auto-generated method stub

}

@Override

public void jobsPaused(String jobGroup) {

// TODO Auto-generated method stub

}

@Override

public void jobResumed(JobKey jobKey) {

// TODO Auto-generated method stub

}

@Override

public void jobsResumed(String jobGroup) {

// TODO Auto-generated method stub

}

@Override

public void schedulerError(String msg, SchedulerException cause) {

// TODO Auto-generated method stub

}

@Override

public void schedulerInStandbyMode() {

// TODO Auto-generated method stub

}

@Override

public void schedulerStarted() {

// TODO Auto-generated method stub

}

@Override

public void schedulerStarting() {

// TODO Auto-generated method stub

}

@Override

public void schedulerShutdown() {

// TODO Auto-generated method stub

}

@Override

public void schedulerShuttingdown() {

// TODO Auto-generated method stub

}

@Override

public void schedulingDataCleared() {

// TODO Auto-generated method stub

}

}

“`

“`

StdSchedulerFactory.getDefaultScheduler().getListenerManager().addSchedulerListener(自定义实现SchedulerListener的类);

“`

#以下是springboot与quartz整合

一、加入配置

“`bash

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-quartz</artifactId>

</dependency>

“`

二、配合SchedulerConfig

“`bash

package com.equipmenttesting.common.quartz.config;

import org.quartz.JobDetail;

import org.quartz.spi.JobFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.quartz.CronTriggerFactoryBean;

import org.springframework.scheduling.quartz.JobDetailFactoryBean;

import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.io.IOException;

/**

* @program: demo

* @description: quartz动态定时任务配置类

* @author:

*

*/

@Configuration

public class SchedulerConfig {

@Bean

public JobFactory jobFactory(ApplicationContext applicationContext) {

SpringBeanJobFactory jobFactory = new SpringBeanJobFactory();

jobFactory.setApplicationContext(applicationContext);

return jobFactory;

}

/**调度工厂bean

* @param jobFactory

* @throws IOException

*/

@Bean

public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws IOException {

SchedulerFactoryBean factory = new SchedulerFactoryBean();

factory.setJobFactory(jobFactory);

//QuartzScheduler 延时启动,应用启动完5秒后 QuartzScheduler 再启动

factory.setStartupDelay(1);

// this allows to update triggers in DB when updating settings in config file:

//用于quartz集群,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了

factory.setOverwriteExistingJobs(true);

//用于quartz集群,加载quartz数据源

// factory.setDataSource(dataSource);

//用于quartz集群,加载quartz数据源配置

// factory.setQuartzProperties(quartzProperties());

//注册触发器

//factory.setTriggers(cronJobTrigger);

return factory;

}

/**加载quartz数据源配置,quartz集群时用到

* @return

* @throws IOException

*/

// @Bean

// public Properties quartzProperties() throws IOException {

// PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();

// propertiesFactoryBean.setLocation(new ClassPathResource(“/quartz.properties”));

// propertiesFactoryBean.afterPropertiesSet();

// return propertiesFactoryBean.getObject();

// }

/**

* 创建触发器工厂

* @param jobClass

* @return

*/

private static JobDetailFactoryBean createJobDetail(Class jobClass) {

JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();

factoryBean.setJobClass(jobClass);

factoryBean.setDurability(true);

return factoryBean;

}

/**创建定时器工厂

* @param jobDetail

* @return

*/

private static CronTriggerFactoryBean createTrigger(JobDetail jobDetail) {

CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();

factoryBean.setJobDetail(jobDetail);

factoryBean.setStartDelay(0L);

factoryBean.setCronExpression (“0/1 * * * * ? “);//每1秒执行一次

return factoryBean;

}

}

“`

三、新建数据库表

“`bash

DROP TABLE IF EXISTS `t_schedule_job`;

CREATE TABLE `t_schedule_job` (

`id` char(36) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘任务主键’,

`task_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘任务名称’,

`task_group` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘任务分组’,

`class_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘class类名称地址’,

`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘任务描述’,

`cron_expression` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘时间设置(定时器时间格式)’,

`task_status` int(1) NULL DEFAULT NULL COMMENT ‘0: 执行 1: 暂停’,

`is_enable` int(1) NULL DEFAULT NULL COMMENT ‘0:启用 1:停用’,

`update_time` datetime(6) NULL DEFAULT NULL COMMENT ‘更新时间’,

`create_time` datetime(6) NULL DEFAULT NULL COMMENT ‘创建时间’,

`create_user` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘创建人’,

PRIMARY KEY (`id`) USING BTREE

) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

SET FOREIGN_KEY_CHECKS = 1;

“`

插入一条语句

“`bash

INSERT INTO `t_schedule_job`(`id`, `task_name`, `task_group`, `class_name`, `description`, `cron_expression`, `task_status`, `is_enable`, `update_time`, `create_time`, `create_user`) VALUES (‘c4d1c93b-a98c-4a8d-b555-0c2bb87e3a48’, ‘wer设备检测’, ‘device’, ‘com.equipmenttesting.project.timer.QuartzSchedulerJob’, ‘设备自动检测’, ‘0/1 * * * * ?’, 1, 1, ‘2020-01-12 11:13:25.567000’, ‘2020-01-12 11:13:06.733000’, ‘admin’);

“`

四、建表的domain类 我这里用到了lombok插件 也可以直接getset

“`bash

import com.equipmenttesting.common.baseDomain.BaseDomain;

import lombok.*;

import java.util.Date;

/**

* @Description

*/

@Getter

@Setter

@AllArgsConstructor

@NoArgsConstructor

public class MgrScheduleJob extends BaseDomain {

private static final long serialVersionUID = 515061450646512139L;

/**

* 任务名称

*/

private String taskName;

/**

* 任务分组

*/

private String taskGroup;

/**

* class类名称地址

*/

private String className;

/**

* 任务描述

*/

private String description;

/**

* 时间设置(定时器时间格式)

*/

private String cronExpression;

/**

* 0:执行 1:暂停

*/

private Integer taskStatus;

/**

* 0:启用 1:停用

*/

private Integer isEnable;

/**

* 更新时间

*/

private Date updateTime;

/**

* 创建时间

*/

private Date createTime;

/**

* 创建人

*/

private String createUser;

}

“`

五、实现定时任务的增删改查

service

“`bash

import com.equipmenttesting.project.quartztask.domain.MgrScheduleJob;

import org.quartz.SchedulerException;

import java.util.List;

/**

* @program: demo

* @description: quartz定时任务Service

* @author:

* @create:

*/

public interface IJobAndTriggerService {

/**

* 新增任务

* @param scheduleJob

* @throws Exception

*/

void addOrUpdateJob(MgrScheduleJob scheduleJob) throws Exception;

/**

* Scheduler 删除定时任务

* @param scheduleJob

* @throws Exception

*/

void stopJob(MgrScheduleJob scheduleJob) throws SchedulerException;

/**

* Scheduler 暂停定时任务

* @param scheduleJob

* @throws Exception

*/

void pauseJob(MgrScheduleJob scheduleJob) throws SchedulerException;

/**

* Scheduler 恢复定时任务

* @param scheduleJob

* @throws Exception

*/

void resumejob(MgrScheduleJob scheduleJob) throws SchedulerException;

/**

* 立即执行一个job

* @param scheduleJob

* @throws SchedulerException

*/

void runAJobNow(MgrScheduleJob scheduleJob) throws SchedulerException;

/**

* 获取所有计划中的任务列表

* @return

* @throws SchedulerException

*/

List<MgrScheduleJob> getAllJob() throws SchedulerException;

/**

* 获取所有执行中的任务列表

* @return

* @throws SchedulerException

*/

List<MgrScheduleJob> getRunningJob() throws SchedulerException;

/**

* 暂停所有任务

* @throws SchedulerException

*/

void pauseAllJobs() throws SchedulerException;

/**

* 恢复所有任务

* @throws SchedulerException

*/

void resumeAllJobs() throws SchedulerException;

}

“`

serverImpl

“`bash

import com.equipmenttesting.project.quartztask.domain.MgrScheduleJob;

import com.equipmenttesting.project.quartztask.mapper.QuartzMapper;

import com.equipmenttesting.project.quartztask.service.IJobAndTriggerService;

import com.sun.xml.internal.bind.v2.model.core.ID;

import lombok.extern.slf4j.Slf4j;

import org.quartz.*;

import org.quartz.impl.matchers.GroupMatcher;

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

import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import org.springframework.stereotype.Service;

import org.springframework.util.Assert;

import javax.annotation.PostConstruct;

import java.util.*;

/**

* @program: demo

* @description: quartz定时任务实现类

* @author:

* @create:

*/

/**

* Scheduler:调度器,进行任务调度;quartz的大脑

* Job:业务job,亦可称业务组件;定时任务的具体执行业务需要实现此接口,调度器会调用此接口的execute方法完成我们的定时业务

* JobDetail:用来定义业务Job的实例,我们可以称之为quartz job,很多时候我们谈到的job指的是JobDetail

* Trigger:触发器,用来定义一个指定的Job何时被执行

* JobBuilder:Job构建器,用来定义或创建JobDetail的实例;JobDetail限定了只能是Job的实例

* TriggerBuilder:触发器构建器,用来定义或创建触发器的实例

*/

@Slf4j

@Service

public class JobAndTriggerServiceImpl implements IJobAndTriggerService {

@Autowired

private SchedulerFactoryBean schedulerFactoryBean;

@Autowired

private QuartzMapper quartzMapper;

/**

* 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。

* @throws Exception

*/

@PostConstruct

public void init() {

Map map= new HashMap<>();

map.put(“isEnable”,0);

// 这里获取任务信息数据

List<MgrScheduleJob> jobList = quartzMapper.getAllMgrScheduleJob(map);

List<MgrScheduleJob> mgrScheduleJobs=new ArrayList<>();

System.out.println(jobList);

jobList.forEach(job -> {

try {

if ( job !=null && job.getTaskStatus() !=null & job.getTaskStatus() == 1){

job.setTaskStatus(0);

mgrScheduleJobs.add(job);

}

addOrUpdateJob(job);

} catch (Exception e) {

log.error(“初始化定时任务列表异常—>{}”,e.getMessage());

}

});

if(mgrScheduleJobs.size()>0){

quartzMapper.updateAllMgrScheduleJob(mgrScheduleJobs);

}

}

@Override

public void addOrUpdateJob(MgrScheduleJob mgrScheduleJob) throws Exception {

//获去调度器实例

Scheduler scheduler = schedulerFactoryBean.getScheduler();

TriggerKey triggerKey = TriggerKey.triggerKey(mgrScheduleJob.getTaskName(), mgrScheduleJob.getTaskGroup());

CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

//trigger不存在,创建一个

if (null == trigger) {

//新增定时任务

Class clazz = Class.forName(mgrScheduleJob.getClassName());

//判断clazz是否为null,是则抛出异常

Assert.notNull(clazz, “定时任务执行类为NULL”);

//初始化一个类,生成一个实例

clazz.newInstance();

// 构建job信息

JobDetail jobDetail = JobBuilder.newJob(clazz)

.withIdentity(mgrScheduleJob.getTaskName(),mgrScheduleJob.getTaskGroup()).build();

// 表达式调度构建器(即任务执行的时间)

CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(mgrScheduleJob.getCronExpression());

// 按新的cronExpression表达式构建一个新的trigger

trigger = TriggerBuilder.newTrigger().withIdentity(mgrScheduleJob.getTaskName(),mgrScheduleJob.getTaskGroup())

.withSchedule(scheduleBuilder).build();

//设置job执行

scheduler.scheduleJob(jobDetail, trigger);

} else {

// Trigger已存在,那么更新相应的定时设置

CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(mgrScheduleJob.getCronExpression());

// 按新的cronExpression表达式重新构建trigger

trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

// 按新的trigger重新设置job执行

scheduler.rescheduleJob(triggerKey, trigger);

}

}

@Override

public void stopJob(MgrScheduleJob scheduleJob) throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup());

scheduler.deleteJob(jobKey);

}

@Override

public void pauseJob(MgrScheduleJob scheduleJob) throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup());

scheduler.pauseJob(jobKey);

}

@Override

public void resumejob(MgrScheduleJob scheduleJob) throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup());

scheduler.resumeJob(jobKey);

}

@Override

public void runAJobNow(MgrScheduleJob scheduleJob) throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

JobKey jobKey = JobKey.jobKey(scheduleJob.getTaskName(), scheduleJob.getTaskGroup());

scheduler.triggerJob(jobKey);

}

@Override

public List<MgrScheduleJob> getAllJob() throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

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

GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();

Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);

jobKeys.forEach(jobKey -> {

List<? extends Trigger> triggers = null;

try {

triggers = scheduler.getTriggersOfJob(jobKey);

} catch (SchedulerException e) {

e.printStackTrace();

}

if (triggers != null) {

triggers.forEach(trigger -> {

MgrScheduleJob job = new MgrScheduleJob();

job.setTaskName(jobKey.getName());

job.setTaskGroup(jobKey.getGroup());

if (trigger instanceof CronTrigger) {

CronTrigger cronTrigger = (CronTrigger) trigger;

String cronExpression = cronTrigger.getCronExpression();

job.setCronExpression(cronExpression);

}

jobList.add(job);

});

}

});

return jobList;

}

@Override

public List<MgrScheduleJob> getRunningJob() throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();

List<MgrScheduleJob> jobList = new ArrayList<MgrScheduleJob>(executingJobs.size());

for (JobExecutionContext executingJob : executingJobs) {

MgrScheduleJob job = new MgrScheduleJob();

JobDetail jobDetail = executingJob.getJobDetail();

JobKey jobKey = jobDetail.getKey();

job.setTaskName(jobKey.getName());

job.setTaskGroup(jobKey.getGroup());

Trigger trigger = executingJob.getTrigger();

// Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());

if (trigger instanceof CronTrigger) {

CronTrigger cronTrigger = (CronTrigger) trigger;

String cronExpression = cronTrigger.getCronExpression();

job.setCronExpression(cronExpression);

}

jobList.add(job);

}

return jobList;

}

@Override

public void pauseAllJobs() throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

scheduler.pauseAll();

}

@Override

public void resumeAllJobs() throws SchedulerException {

Scheduler scheduler = schedulerFactoryBean.getScheduler();

scheduler.resumeAll();

}

}

“`

六、然后就可以实现定时任务了的增删改查了

service

“`bash

import com.equipmenttesting.project.quartztask.domain.MgrScheduleJob;

/**

* @program: demo

* @description: 定时任务实体Service类

* @author:

* @create:

*/

public interface IScheduleJobService {

/**

* 添加或新增定时任务

* @param mgrScheduleJob

* @throws Exception

*/

void addOrUpdateScheduleJob(MgrScheduleJob mgrScheduleJob) throws Exception;

/**

* 修改定时任务启用状态 0 启用 1 停用

* @param id

* @throws Exception

*/

void isEnableScheduleJob(String id) throws Exception;

/**

* 暂停/恢复 定时任务

* @param id

* @throws Exception

*/

void pauseScheduleJob(String id) throws Exception;

/**

* 删除定时任务

* @param id

* @throws Exception

*/

void deleteScheduleJob(String id) throws Exception;

/**

* 立即运行定时任务

* @param id

* @throws Exception

*/

void runScheduleJob(String id) throws Exception;

}

“`

serviceImpl

“`bash

import com.equipmenttesting.project.quartztask.domain.MgrScheduleJob;

import com.equipmenttesting.project.quartztask.mapper.QuartzMapper;

import com.equipmenttesting.project.quartztask.service.IJobAndTriggerService;

import com.equipmenttesting.project.quartztask.service.IScheduleJobService;

import com.github.pagehelper.util.StringUtil;

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

import org.springframework.stereotype.Service;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

/**

* @program: demo

* @description: 定时任务Service实现类

* @author:

* @create:

*/

@Service

public class ScheduleJobServiceImpl implements IScheduleJobService {

@Autowired

private IJobAndTriggerService jobAndTriggerService;

@Autowired

public QuartzMapper quartzMapper;

@Override

public void addOrUpdateScheduleJob(MgrScheduleJob mgrScheduleJob) throws Exception {

if (StringUtil.isNotEmpty(mgrScheduleJob.getId())){

//更新任务

mgrScheduleJob.setTaskStatus(0);

mgrScheduleJob.setIsEnable(0);

mgrScheduleJob.setUpdateTime(new Date());

quartzMapper.updateMgrScheduleJob(mgrScheduleJob);

}else {

//新增任务

mgrScheduleJob.setTaskStatus(0);

mgrScheduleJob.setIsEnable(0);

mgrScheduleJob.setCreateTime(new Date());

mgrScheduleJob.setUpdateTime(new Date());

quartzMapper.addMgrScheduleJob(mgrScheduleJob);

}

jobAndTriggerService.addOrUpdateJob(mgrScheduleJob);

}

@Override

public void isEnableScheduleJob(String id) throws Exception {

Map map= new HashMap<>();

map.put(“id”,id);

// 这里获取任务信息数据

MgrScheduleJob mgrScheduleJob = quartzMapper.loadMgrScheduleJob(map);

if (mgrScheduleJob.getIsEnable() == 0){

//停用任务

mgrScheduleJob.setIsEnable(1);

quartzMapper.updateMgrScheduleJob(mgrScheduleJob);

jobAndTriggerService.stopJob(mgrScheduleJob);

}else if (mgrScheduleJob.getIsEnable() == 1){

//启用任务

mgrScheduleJob.setIsEnable(0);

quartzMapper.updateMgrScheduleJob(mgrScheduleJob);

jobAndTriggerService.addOrUpdateJob(mgrScheduleJob);

}

}

@Override

public void pauseScheduleJob(String id) throws Exception {

Map map= new HashMap<>();

map.put(“id”,id);

// 这里获取任务信息数据

MgrScheduleJob mgrScheduleJob = quartzMapper.loadMgrScheduleJob(map);

if (mgrScheduleJob.getTaskStatus() == 0){

//暂停任务

mgrScheduleJob.setTaskStatus(1);

quartzMapper.updateMgrScheduleJob(mgrScheduleJob);

jobAndTriggerService.pauseJob(mgrScheduleJob);

}else if (mgrScheduleJob.getTaskStatus() == 1){

//执行任务

mgrScheduleJob.setTaskStatus(0);

quartzMapper.updateMgrScheduleJob(mgrScheduleJob);

jobAndTriggerService.resumejob(mgrScheduleJob);

}

}

@Override

public void deleteScheduleJob(String id) throws Exception {

Map map= new HashMap<>();

map.put(“id”,id);

// 这里获取任务信息数据

MgrScheduleJob mgrScheduleJob = quartzMapper.loadMgrScheduleJob(map);

jobAndTriggerService.stopJob(mgrScheduleJob);

quartzMapper.deleteMgrScheduleJobById(map);

}

@Override

public void runScheduleJob(String id) throws Exception {

Map map= new HashMap<>();

map.put(“id”,id);

// 这里获取任务信息数据

MgrScheduleJob mgrScheduleJob = quartzMapper.loadMgrScheduleJob(map);

jobAndTriggerService.runAJobNow(mgrScheduleJob);

}

}

“`

Controller

“`bash

import com.equipmenttesting.project.quartztask.domain.MgrScheduleJob;

import com.equipmenttesting.project.quartztask.service.IScheduleJobService;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.ApiParam;

import lombok.extern.slf4j.Slf4j;

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

import org.springframework.web.bind.annotation.*;

/**

* @program: demo

* @description: 定时任务Controller

* @author:

* @create:

*/

@Api(tags = “定时任务管理模块”,description = “ScheduleJobController”)

@Slf4j

@RestController

@RequestMapping(“sys/schedule”)

public class ScheduleJobController {

@Autowired

private IScheduleJobService scheduleJobService;

@ApiOperation(“添加或更新定时任务”)

@PostMapping(“add”)

public String addOrUpdate(@RequestBody MgrScheduleJob mgrScheduleJob){

try {

scheduleJobService.addOrUpdateScheduleJob(mgrScheduleJob);

return “定时任务添加或更新成功”;

} catch (Exception e) {

log.error(“定时任务新增或更新失败==>【{}】”,e.getMessage());

return “定时任务添加或更新失败”;

}

}

@ApiOperation(“删除定时任务”)

@PostMapping(“delete”)

public String delete(@ApiParam(value = “”,required = true) @RequestParam String id){

try {

scheduleJobService.deleteScheduleJob(id);

return “删除定时任务成功”;

} catch (Exception e) {

log.error(“删除定时任务失败==>【{}】”,e.getMessage());

return “删除定时任务失败”;

}

}

@ApiOperation(“启用或停用定时任务”)

@PostMapping(“isEnable”)

public String isEnable(@ApiParam(value = “”,required = true) @RequestParam String id){

try {

scheduleJobService.isEnableScheduleJob(id);

return “启用或停用定时任务成功”;

} catch (Exception e) {

log.error(“启用或停用定时任务失败==>【{}】”,e.getMessage());

return “启用或停用定时任务失败”;

}

}

@ApiOperation(“暂停或执行定时任务”)

@PostMapping(“pauseJob”)

public String pauseJob(@ApiParam(value = “”,required = true) @RequestParam String id){

try {

scheduleJobService.pauseScheduleJob(id);

return “暂停或执行定时任务成功”;

} catch (Exception e) {

log.error(“暂停或执行定时任务失败==>【{}】”,e.getMessage());

return “暂停或执行定时任务失败”;

}

}

}

“`

七、mapper

mapper.java

“`bash

import java.util.List;

import java.util.Map;

/**

* TODO

*

* @author Administrator

* @date 2020/1/11 13:26

**/

public interface QuartzMapper {

List<MgrScheduleJob> getAllMgrScheduleJob(Map map);

void updateAllMgrScheduleJob(List<MgrScheduleJob> mgrScheduleJob);

void updateMgrScheduleJob(MgrScheduleJob mgrScheduleJobs);

void addMgrScheduleJob(MgrScheduleJob mgrScheduleJobs);

MgrScheduleJob loadMgrScheduleJob(Map map);

void deleteMgrScheduleJobById(Map map);

}

“`

mapper.xml

“`bash

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<!DOCTYPE mapper

PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN”

“http://mybatis.org/dtd/mybatis-3-mapper.dtd”>

<mapper namespace=”com.equipmenttesting.project.quartztask.mapper.QuartzMapper”>

<resultMap id=”mgrScheduleJobs” type=”MgrScheduleJob”>

<id property=”id” column=”id”/>

<result column=”task_name” property=”taskName” />

<result property=”taskGroup” column=”task_group”/>

<result property=”className” column=”class_name”/>

<result property=”description” column=”description”/>

<result property=”cronExpression” column=”cron_expression”/>

<result property=”taskStatus” column=”task_status”/>

<result property=”isEnable” column=”is_enable”/>

<result property=”updateTime” column=”update_time”/>

<result property=”createTime” column=”create_time”/>

<result property=”createUser” column=”create_user”/>

</resultMap>

<select id=”getAllMgrScheduleJob” parameterType=”MgrScheduleJob” resultMap=”mgrScheduleJobs”>

select * from t_schedule_job where IS_ENABLE=#{isEnable}

</select>

<update id=”updateAllMgrScheduleJob” parameterType=”java.util.List” >

<foreach collection=”list” item=”MgrScheduleJob” index=”index” open=”” close=”” separator=”;”>

update t_schedule_job

<set>

task_name=#{MgrScheduleJob.taskName},

task_group=#{MgrScheduleJob.taskGroup},

class_name= #{MgrScheduleJob.className},

description=#{MgrScheduleJob.description},

cron_expression=#{MgrScheduleJob.cronExpression},

task_status=#{MgrScheduleJob.taskStatus},

is_enable=#{MgrScheduleJob.isEnable},

update_time= #{MgrScheduleJob.updateTime},

create_time= #{MgrScheduleJob.createTime},

create_user= #{MgrScheduleJob.createUser}

</set>

where id=#{MgrScheduleJob.id}

</foreach>

</update>

<update id=”updateMgrScheduleJob” parameterType=”MgrScheduleJob” >

update t_schedule_job

<set>

task_name=#{taskName},

task_group=#{taskGroup},

class_name= #{className},

description=#{description},

cron_expression=#{cronExpression},

task_status=#{taskStatus},

is_enable=#{isEnable},

update_time= #{updateTime},

create_time= #{createTime},

create_user= #{createUser}

</set>

where id=#{id}

</update>

<insert id=”addMgrScheduleJob” parameterType=”MgrScheduleJob”>

insert into t_schedule_job(

id,

TASK_NAME,

TASK_GROUP,

CLASS_NAME,

DESCRIPTION,

CRON_EXPRESSION,

TASK_STATUS,

IS_ENABLE,

UPDATE_TIME,

CREATE_TIME,

CREATE_USER

) values (

#{id},

#{taskName},

#{taskGroup},

#{className},

#{description},

#{cronExpression},

#{taskStatus},

#{isEnable},

#{updateTime},

#{createTime},

#{createUser}

)

</insert>

<select id=”loadMgrScheduleJob” parameterType=”map” resultMap=”mgrScheduleJobs”>

select * from t_schedule_job where id=#{id}

</select>

<delete id=”deleteMgrScheduleJobById” parameterType=”map” >

delete from t_schedule_job where id=#{id}

</delete>

</mapper>

“`

测试定时任务

“`bash

import lombok.extern.slf4j.Slf4j;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;

/**

* @program: demo

* @description: 测试定时任务类

* @author:

* @create:

*

* QuartzJobBean implements Job

*/

@Slf4j

public class QuartzSchedulerJob extends QuartzJobBean {

@Override

protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

log.info(“执行测试定时任务==>【{}】”, LocalDateTime.now());

System.out.println(“执行测试定时任务==>【{}】”);

}

}

“`

以上基本步骤已经完成

如果想在别的地方添加定时任务则需要添加t_schedule_job 表的数据和调用IJobAndTriggerService.java 的增删改查了

[参考的文章](https://www.cnblogs.com/1994july/p/12163935.html)

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/12903.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信