简单区分:

RAM:程序启动从数据库中读取原始job配置(也可以从配置文件中读取),job中间运行过程在RAM内存中,程序停止或重启后,RAM中数据丢失,再次启动的时候会重新读取job配置。适合于单机使用

JDBC:程序启动从数据库中读取原始job配置,job中间运行过程存在JDBC中,程序停止或重启后,JDBC中数据不丢失,适合于集群使用。

1、jar包依赖引入

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

2、yml配置文件

  quartz:
properties:
org:
quartz:
scheduler:
instanceName: quartzScheduler
instanceId: AUTO
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true

3、实体类SysQuartzramJob

package org.jeecg.modules.quartz.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.jeecgframework.poi.excel.annotation.Excel; /**
* @Description: 定时任务RAM,
* @author: dengjie
* @Date: 2022-02-16
* @Version: V1.0
*/
@Data
@TableName("sys_quartz_job_ram")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="sys_quartz_job_ram对象", description="定时任务RAM")
public class SysQuartzramJob { //名字和分组,定好了就不能改,切记。定时器内部核心逻辑是根据名字和分组去标识一个定时任务的
/**id*/
@TableId(type = IdType.ID_WORKER_STR)
@ApiModelProperty(value = "id")
private String id;
/**任务名称*/
@Excel(name = "任务名称", width = 15)
@ApiModelProperty(value = "任务名称")
private String jobName;
/**任务分组*/
@Excel(name = "任务分组", width = 15)
@ApiModelProperty(value = "任务分组")
private String jobGroup;
/**执行类*/
@Excel(name = "执行类", width = 15)
@ApiModelProperty(value = "执行类")
private String jobClassName;
/**执行时间*/
@Excel(name = "执行时间", width = 15)
@ApiModelProperty(value = "执行时间")
private String cronExpression;
/**任务状态*/
@Excel(name = "任务状态", width = 15)
@ApiModelProperty(value = "任务状态")
private String triggerState;
/**描述*/
@Excel(name = "描述", width = 15)
@ApiModelProperty(value = "描述")
private String description; /**下面是实体对应数据库的表sys_quartzram_job
*
* CREATE TABLE "public"."sys_quartzram_job" (
* "id" varchar(50) ,
* "job_name" varchar(50) COLLATE "pg_catalog"."default",
* "job_group" varchar(50) COLLATE "pg_catalog"."default",
* "job_class_name" varchar(100) COLLATE "pg_catalog"."default",
* "cron_expression" varchar(100) COLLATE "pg_catalog"."default",
* "trigger_state" varchar(15) COLLATE "pg_catalog"."default",
* "description" varchar(100) COLLATE "pg_catalog"."default"
* )
* ;
*
* COMMENT ON COLUMN "public"."sys_quartzram_job"."id" IS 'id';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."job_name" IS '任务名称';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."job_group" IS '任务分组';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."job_class_name" IS '执行类';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."cron_expression" IS '执行时间';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."trigger_state" IS '任务状态';
* COMMENT ON COLUMN "public"."sys_quartzram_job"."description" IS '描述';
*
*/
}

4、核心controller类

package org.jeecg.modules.quartz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.quartz.entity.SysQuartzramJob;
import org.jeecg.modules.quartz.enums.JobStatus;
import org.jeecg.modules.quartz.service.ISysQuartzramJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays; /**
* @Description: 定时任务RAM
* @author: dengjie
* @Date: 2022-02-16
* @Version: V1.0
*/
@Slf4j
@Api(tags="定时任务RAM")
@RestController
@RequestMapping("/quartz/sysQuartzramJob")
public class SysQuartzramJobController extends JeecgController<SysQuartzramJob, ISysQuartzramJobService> {
private static final String TRIGGER_IDENTITY = "trigger";
@Autowired
private ISysQuartzramJobService sysQuartzramJobService;
@Autowired
private Scheduler scheduler;
/**
* 分页列表查询
*
* @param sysQuartzramJob
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@AutoLog(value = "定时任务RAM-分页列表查询")
@ApiOperation(value="定时任务RAM-分页列表查询", notes="定时任务RAM-分页列表查询")
@GetMapping(value = "/list")
public Result<?> queryPageList(SysQuartzramJob sysQuartzramJob,
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<SysQuartzramJob> queryWrapper = QueryGenerator.initQueryWrapper(sysQuartzramJob, req.getParameterMap());
Page<SysQuartzramJob> page = new Page<SysQuartzramJob>(pageNo, pageSize);
IPage<SysQuartzramJob> pageList = sysQuartzramJobService.page(page, queryWrapper);
return Result.ok(pageList);
} /**
* 添加
*
* @param sysQuartzramJob
* @return
*/
@AutoLog(value = "定时任务RAM-添加")
@ApiOperation(value="定时任务RAM-添加", notes="定时任务RAM-添加")
@PostMapping(value = "/add")
public Result<?> add(@RequestBody SysQuartzramJob sysQuartzramJob) {
try
{
schedulerJob(sysQuartzramJob);
sysQuartzramJob.setTriggerState(JobStatus.RUNNING.getStatus());
sysQuartzramJobService.save(sysQuartzramJob);
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
} @AutoLog(value = "定时任务RAM-触发")
@ApiOperation(value="定时任务RAM-触发", notes="定时任务RAM-触发")
@PostMapping(value = "/trigger")
public Result<?> trigger(@RequestBody SysQuartzramJob sysQuartzramJob) {
try
{
JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
scheduler.triggerJob(key);
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
} @AutoLog(value = "定时任务RAM-停止")
@ApiOperation(value="定时任务RAM-停止", notes="定时任务RAM-停止")
@PostMapping(value = "/pause")
public Result<?> pause(@RequestBody SysQuartzramJob sysQuartzramJob) {
try
{
JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
scheduler.pauseJob(key); sysQuartzramJob.setTriggerState(JobStatus.PAUSED.getStatus());
sysQuartzramJobService.updateById(sysQuartzramJob);
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
} @AutoLog(value = "定时任务RAM-恢复")
@ApiOperation(value="定时任务RAM-恢复", notes="定时任务RAM-恢复")
@PostMapping(value = "/resume")
public Result<?> resume(@RequestBody SysQuartzramJob sysQuartzramJob) {
try
{
JobKey key = new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup());
scheduler.resumeJob(key); sysQuartzramJob.setTriggerState(JobStatus.RUNNING.getStatus());
sysQuartzramJobService.updateById(sysQuartzramJob);
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
} @AutoLog(value = "定时任务RAM-删除")
@ApiOperation(value="定时任务RAM-删除", notes="定时任务RAM-删除")
@PostMapping(value = "/delete")
public Result<?> delete(@RequestBody SysQuartzramJob sysQuartzramJob) {
try
{
String jobName=sysQuartzramJob.getJobName();
String jobGroup=sysQuartzramJob.getJobGroup(); TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_IDENTITY + jobName, jobGroup);
scheduler.pauseTrigger(triggerKey); // 停止触发器
scheduler.unscheduleJob(triggerKey); // 移除触发器
scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup)); // 删除任务 sysQuartzramJobService.removeById(sysQuartzramJob.getId());
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
}
/**
* 编辑
*
* @param sysQuartzramJob
* @return
*/
@AutoLog(value = "定时任务RAM-编辑")
@ApiOperation(value="定时任务RAM-编辑", notes="定时任务RAM-编辑")
@PutMapping(value = "/edit")
public Result<?> edit(@RequestBody SysQuartzramJob sysQuartzramJob) { try
{
scheduler.deleteJob(new JobKey(sysQuartzramJob.getJobName(),sysQuartzramJob.getJobGroup()));
schedulerJob(sysQuartzramJob); sysQuartzramJobService.updateById(sysQuartzramJob);
}
catch (Exception e) {
e.printStackTrace();
return Result.error("异常:" + e.getMessage());
} return Result.ok("成功!");
} /**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "定时任务RAM-批量删除")
@ApiOperation(value="定时任务RAM-批量删除", notes="定时任务RAM-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
this.sysQuartzramJobService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
} /**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "定时任务RAM-通过id查询")
@ApiOperation(value="定时任务RAM-通过id查询", notes="定时任务RAM-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
SysQuartzramJob sysQuartzramJob = sysQuartzramJobService.getById(id);
return Result.ok(sysQuartzramJob);
} /**
* 导出excel
*
* @param request
* @param sysQuartzramJob
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysQuartzramJob sysQuartzramJob) {
return super.exportXls(request, sysQuartzramJob, SysQuartzramJob.class, "定时任务RAM");
} /**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysQuartzramJob.class);
} public void schedulerJob(SysQuartzramJob job) throws Exception {
//构建job信息
Class cls = Class.forName(job.getJobClassName()) ;
// cls.newInstance(); // 检验类是否存在
JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
.withDescription(job.getDescription()).build(); // 触发时间点
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression().trim());
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_IDENTITY + job.getJobName(), job.getJobGroup())
.startNow().withSchedule(cronScheduleBuilder).build();
//交由Scheduler安排触发
scheduler.scheduleJob(jobDetail, trigger);
} }

5、定时任务初始化类

程序启动后,会自动执行ApplicationInit类,并读取定时任务进行开始执行调度
package org.jeecg.modules.quartz.init;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.quartz.entity.SysQuartzramJob;
import org.jeecg.modules.quartz.enums.JobStatus;
import org.jeecg.modules.quartz.service.ISysQuartzramJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component; import java.io.IOException;
import java.io.InputStream;
import java.util.List; @Component
@Slf4j
public class ApplicationInit implements CommandLineRunner { private static final String TRIGGER_IDENTITY = "trigger";
@Autowired
private ISysQuartzramJobService sysQuartzramJobService;
@Autowired
private Scheduler scheduler; @Override
public void run(String... args) throws Exception { log.info(String.format("程序启动,定时任务开始加载,时间:" + DateUtils.getTimestamp())); loadJobFromDB();
} //这是从数据库表读取定时任务的逻辑
private void loadJobFromDB() throws Exception {
try { QueryWrapper<SysQuartzramJob> queryWrapper = new QueryWrapper<SysQuartzramJob>();
List<SysQuartzramJob> list=sysQuartzramJobService.list(queryWrapper);
for(SysQuartzramJob job : list)
{
schedulerJob(job);
if (JobStatus.PAUSED.getStatus().equals(job.getTriggerState())) {
scheduler.pauseJob(new JobKey(job.getJobName(), job.getJobGroup()));
}
} }
catch (Exception e)
{
log.error(e.getMessage(),e);
}
} public void schedulerJob(SysQuartzramJob job) throws Exception {
//构建job信息
Class cls = Class.forName(job.getJobClassName()) ;
// cls.newInstance(); // 检验类是否存在
JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
.withDescription(job.getDescription()).build(); // 触发时间点
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression().trim());
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TRIGGER_IDENTITY + job.getJobName(), job.getJobGroup())
.startNow().withSchedule(cronScheduleBuilder).build();
//交由Scheduler安排触发
scheduler.scheduleJob(jobDetail, trigger);
}
}

6、job定时任务样例

package org.jeecg.modules.quartz.job;

import org.jeecg.common.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException; import lombok.extern.slf4j.Slf4j; /**
* 示例不带参定时任务
*
* @Author Scott
*/
@Slf4j
public class SampleJob implements Job { @Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info(String.format(" Jeecg-Boot 普通定时任务 SampleJob ! 时间:" + DateUtils.getTimestamp()));
}
}

本文参考了最佳实践博文:https://www.cnblogs.com/youzhibing/p/10208056.html

spring-boot集成Quartz-job存储方式二RAM的更多相关文章

  1. spring boot集成pagehelper(两种方式)

    当spring boot集成好mybatis时候需要进行分页,我们首先添加maven支持 <dependency> <groupId>com.github.pagehelper ...

  2. Spring Boot集成quartz实现定时任务并支持切换任务数据源

    org.quartz实现定时任务并自定义切换任务数据源 在工作中经常会需要使用到定时任务处理各种周期性的任务,org.quartz是处理此类定时任务的一个优秀框架.随着项目一点点推进,此时我们并不满足 ...

  3. spring boot 集成 quartz 定时任务

    spring boot: @EnableScheduling开启计划任务支持,@Scheduled计划任务声明 1.pom.xml 引入依赖 <dependency> <groupI ...

  4. Spring Boot集成Quartz注入Spring管理的类

    摘要: 在Spring Boot中使用Quartz时,在JOB中一般需要引用Spring管理的Bean,通过定义Job Factory实现自动注入. Spring有自己的Schedule定时任务,在S ...

  5. Spring boot 集成三种定时任务方式

    三种定时任务方式分别为 org.springframework.scheduling.annotation.Scheduled java.util.concurrent.ScheduledExecut ...

  6. Spring boot 集成三种拦截方式

    三种拦截方式分别为: javax.servlet.Filter org.springframework.web.servlet.HandlerInterceptor org.aspectj.lang. ...

  7. Quartz与Spring Boot集成使用

    上次自己搭建Quartz已经是几年前的事了,这次项目中需要定时任务,需要支持集群部署,想到比较轻量级的定时任务框架就是Quartz,于是来一波. 版本说明 通过搜索引擎很容易找到其官网,来到Docum ...

  8. Spring Boot集成持久化Quartz定时任务管理和界面展示

    本文是对之前的一篇文章Spring+SpringMVC+mybatis+Quartz整合代码部分做的一个修改和补充, 其中最大的变化就是后台框架变成了Spring Boot. 本工程所用到的技术或工具 ...

  9. Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

    上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...

  10. Spring Boot集成MyBatis的2种方式

    目录 写在前面 准备工作 配置数据库驱动 配置数据源 原生集成MyBatis 依赖配置 注册MyBatis核心组件 定义并使用映射器 通过MyBatis-Spring-Boot-Starter集成 默 ...

随机推荐

  1. 4 HTML表格标签

    4 表格标签 表格标签也是一种复合标签.由:table,tr,td,th,thead,tbody组合,由行和列组合成,行和列交叉的地方就是单元格.在HTML中使用table来定义表格.网页的表格和办公 ...

  2. Qt 操作注册表

    一.写入注册表 #include <QSettings> //实例 QSettings //参数 1:注册表位置 //参数 2:操作 windows 注册表 QSettings::Nati ...

  3. recover database until cancel

    数据库演示版本为 12.1.0.2 该系列涉及恢复过程中使用的 5 个语句: 1. recover database 2. recover database until cancel 3. recov ...

  4. 可视化学习:使用WebGL绘制圆形,实现色盘

    前言 在Canvas2D中实现圆形的绘制比较简单,只要调用arc指令就能在Canvas画布上绘制出一个圆形,类似的,在SVG中我们也只需要一个<circle>标签就能在页面上绘制一个圆形. ...

  5. ​总结:Apache/Tomcat/JBOSS/Jetty/Nginx之区别和联系​

    总结:Apache/Tomcat/JBOSS/Jetty/Nginx之区别和联系 总结:Apache/Tomcat/JBOSS/Nginx区别 . 1.Apache是Web服务器,Tomcat是应用( ...

  6. Pytorch-tensor的创建,索引,切片

    1.基本概念 标量:就是一个数,是0维的,只有大小,没有方向 向量:是1*n的一列数,是1维的,有大小,也有方向 张量:是n*n的一堆数,是2维的,n个向量合并而成 2.a.size(),a.shap ...

  7. python将日志生成到文件和控制台

    # 日志收集设置import logging, osfrom logging.handlers import TimedRotatingFileHandlerimport datetimecurren ...

  8. 说说你对Node.js 的理解?优缺点?应用场景?

    一.是什么 Node.js 是一个开源与跨平台的 JavaScript 运行时环境 在浏览器外运行 V8 JavaScript 引擎(Google Chrome 的内核),利用事件驱动.非阻塞和异步输 ...

  9. Oracle 与当前日期有关的内容

    Oracle 与当前日期有关的内容 求当前日期是周几: 大概就是下面这种方法 to_char(date,'D') Select to_char(date,'ss') from dual取当前时间秒部分 ...

  10. 力扣190(java)-颠倒二进制位(简单)

    题目: 颠倒给定的 32 位无符号整数的二进制位. 提示: 请注意,在某些语言(如 Java)中,没有无符号整数类型.在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论 ...