初始化 quartz 模块~

This commit is contained in:
YunaiV 2021-02-13 21:13:09 +08:00
parent 2f66829a41
commit c807de1ff8
29 changed files with 440 additions and 855 deletions

View File

@ -151,6 +151,12 @@
<version>1.7.0</version>
</dependency>
<!-- Job 定时任务相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!-- 监控相关 -->
<dependency>
<groupId>org.apache.skywalking</groupId>

View File

@ -1,40 +0,0 @@
package com.ruoyi.common.constant;
/**
* 代码生成通用常量
*
* @author ruoyi
*/
public class GenConstants {
/**
* 树编码字段
*/
public static final String TREE_CODE = "treeCode";
/**
* 树父编码字段
*/
public static final String TREE_PARENT_CODE = "treeParentCode";
/**
* 树名称字段
*/
public static final String TREE_NAME = "treeName";
/**
* 上级菜单ID字段
*/
public static final String PARENT_MENU_ID = "parentMenuId";
/**
* 上级菜单名称字段
*/
public static final String PARENT_MENU_NAME = "parentMenuName";
/**
* Tree基类字段
*/
public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors", "children"};
}

View File

@ -2,30 +2,38 @@ package com.ruoyi.common.constant;
/**
* 任务调度通用常量
*
*
* @author ruoyi
*/
public class ScheduleConstants
{
public class ScheduleConstants {
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */
/**
* 执行目标key
*/
public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */
/**
* 默认
*/
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
/**
* 立即触发执行
*/
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
/**
* 触发一次执行
*/
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
/**
* 不触发立即执行
*/
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
public enum Status {
/**
* 正常
*/
@ -37,13 +45,11 @@ public class ScheduleConstants
private String value;
private Status(String value)
{
private Status(String value) {
this.value = value;
}
public String getValue()
{
public String getValue() {
return value;
}
}

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.3.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-quartz</artifactId>
<description>
quartz定时任务
</description>
<dependencies>
<!-- 定时任务 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<exclusions>
<exclusion>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View File

@ -3,20 +3,19 @@ package com.ruoyi.quartz.config;
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;
/**
* 定时任务配置
*
*
* @author ruoyi
*/
@Configuration
public class ScheduleConfig
{
public class ScheduleConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource)
{
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource);

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.controller;
import java.util.List;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@ -26,13 +27,12 @@ import com.ruoyi.quartz.util.CronUtils;
/**
* 调度任务信息操作处理
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/job")
public class SysJobController extends BaseController
{
public class SysJobController extends BaseController {
@Autowired
private ISysJobService jobService;
@ -41,8 +41,7 @@ public class SysJobController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('monitor:job:list')")
@GetMapping("/list")
public TableDataInfo list(SysJob sysJob)
{
public TableDataInfo list(SysJob sysJob) {
startPage();
List<SysJob> list = jobService.selectJobList(sysJob);
return getDataTable(list);
@ -54,8 +53,7 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:export')")
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJob sysJob)
{
public AjaxResult export(SysJob sysJob) {
List<SysJob> list = jobService.selectJobList(sysJob);
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
return util.exportExcel(list, "定时任务");
@ -66,8 +64,7 @@ public class SysJobController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('monitor:job:query')")
@GetMapping(value = "/{jobId}")
public AjaxResult getInfo(@PathVariable("jobId") Long jobId)
{
public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
return AjaxResult.success(jobService.selectJobById(jobId));
}
@ -77,10 +74,8 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:add')")
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody SysJob sysJob) throws SchedulerException, TaskException
{
if (!CronUtils.isValid(sysJob.getCronExpression()))
{
public AjaxResult add(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
if (!CronUtils.isValid(sysJob.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
sysJob.setCreateBy(SecurityUtils.getUsername());
@ -93,10 +88,8 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:edit')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody SysJob sysJob) throws SchedulerException, TaskException
{
if (!CronUtils.isValid(sysJob.getCronExpression()))
{
public AjaxResult edit(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
if (!CronUtils.isValid(sysJob.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
sysJob.setUpdateBy(SecurityUtils.getUsername());
@ -109,8 +102,7 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException
{
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
SysJob newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
@ -122,8 +114,7 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/run")
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException
{
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException {
jobService.run(job);
return AjaxResult.success();
}
@ -134,8 +125,7 @@ public class SysJobController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobIds}")
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException
{
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -19,13 +20,12 @@ import com.ruoyi.quartz.service.ISysJobLogService;
/**
* 调度日志操作处理
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/jobLog")
public class SysJobLogController extends BaseController
{
public class SysJobLogController extends BaseController {
@Autowired
private ISysJobLogService jobLogService;
@ -34,8 +34,7 @@ public class SysJobLogController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('monitor:job:list')")
@GetMapping("/list")
public TableDataInfo list(SysJobLog sysJobLog)
{
public TableDataInfo list(SysJobLog sysJobLog) {
startPage();
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
return getDataTable(list);
@ -47,20 +46,18 @@ public class SysJobLogController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:export')")
@Log(title = "任务调度日志", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJobLog sysJobLog)
{
public AjaxResult export(SysJobLog sysJobLog) {
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class);
return util.exportExcel(list, "调度日志");
}
/**
* 根据调度编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('monitor:job:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long jobLogId)
{
public AjaxResult getInfo(@PathVariable Long jobLogId) {
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
}
@ -71,8 +68,7 @@ public class SysJobLogController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "定时任务调度日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobLogIds}")
public AjaxResult remove(@PathVariable Long[] jobLogIds)
{
public AjaxResult remove(@PathVariable Long[] jobLogIds) {
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
}
@ -82,8 +78,7 @@ public class SysJobLogController extends BaseController
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "调度日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean()
{
public AjaxResult clean() {
jobLogService.cleanJobLog();
return AjaxResult.success();
}

View File

@ -1,89 +0,0 @@
package com.ruoyi.quartz.domain;
import java.io.Serializable;
import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.util.CronUtils;
/**
* 定时任务调度表 sys_job
*
* @author ruoyi
*/
public class SysJob extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
/** 任务ID */
@Excel(name = "任务序号", cellType = ColumnType.NUMERIC)
private Long jobId;
/** 任务名称 */
@Excel(name = "任务名称")
private String jobName;
/** 任务组名 */
@Excel(name = "任务组名")
private String jobGroup;
/** 调用目标字符串 */
@Excel(name = "调用目标字符串")
private String invokeTarget;
/** cron执行表达式 */
@Excel(name = "执行表达式 ")
private String cronExpression;
/** cron计划策略 */
@Excel(name = "计划策略 ", readConverterExp = "0=默认,1=立即触发执行,2=触发一次执行,3=不触发立即执行")
private String misfirePolicy = ScheduleConstants.MISFIRE_DEFAULT;
/** 是否并发执行0允许 1禁止 */
@Excel(name = "并发执行", readConverterExp = "0=允许,1=禁止")
private String concurrent;
/** 任务状态0正常 1暂停 */
@Excel(name = "任务状态", readConverterExp = "0=正常,1=暂停")
private String status;
@NotBlank(message = "任务名称不能为空")
@Size(min = 0, max = 64, message = "任务名称不能超过64个字符")
public String getJobName()
{
return jobName;
}
@NotBlank(message = "调用目标字符串不能为空")
@Size(min = 0, max = 500, message = "调用目标字符串长度不能超过500个字符")
public String getInvokeTarget()
{
return invokeTarget;
}
@NotBlank(message = "Cron执行表达式不能为空")
@Size(min = 0, max = 255, message = "Cron执行表达式不能超过255个字符")
public String getCronExpression()
{
return cronExpression;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getNextValidTime()
{
if (StringUtils.isNotEmpty(cronExpression))
{
return CronUtils.getNextExecution(cronExpression);
}
return null;
}
}

View File

@ -1,52 +0,0 @@
package com.ruoyi.quartz.domain;
import java.util.Date;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 定时任务调度日志表 sys_job_log
*
* @author ruoyi
*/
public class SysJobLog extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** ID */
@Excel(name = "日志序号")
private Long jobLogId;
/** 任务名称 */
@Excel(name = "任务名称")
private String jobName;
/** 任务组名 */
@Excel(name = "任务组名")
private String jobGroup;
/** 调用目标字符串 */
@Excel(name = "调用目标字符串")
private String invokeTarget;
/** 日志信息 */
@Excel(name = "日志信息")
private String jobMessage;
/** 执行状态0正常 1失败 */
@Excel(name = "执行状态", readConverterExp = "0=正常,1=失败")
private String status;
/** 异常信息 */
@Excel(name = "异常信息")
private String exceptionInfo;
/** 开始时间 */
private Date startTime;
/** 停止时间 */
private Date stopTime;
}

View File

@ -1,64 +0,0 @@
package com.ruoyi.quartz.mapper;
import java.util.List;
import com.ruoyi.quartz.domain.SysJobLog;
/**
* 调度任务日志信息 数据层
*
* @author ruoyi
*/
public interface SysJobLogMapper
{
/**
* 获取quartz调度器日志的计划任务
*
* @param jobLog 调度日志信息
* @return 调度任务日志集合
*/
public List<SysJobLog> selectJobLogList(SysJobLog jobLog);
/**
* 查询所有调度任务日志
*
* @return 调度任务日志列表
*/
public List<SysJobLog> selectJobLogAll();
/**
* 通过调度任务日志ID查询调度信息
*
* @param jobLogId 调度任务日志ID
* @return 调度任务日志对象信息
*/
public SysJobLog selectJobLogById(Long jobLogId);
/**
* 新增任务日志
*
* @param jobLog 调度日志信息
* @return 结果
*/
public int insertJobLog(SysJobLog jobLog);
/**
* 批量删除调度日志信息
*
* @param logIds 需要删除的数据ID
* @return 结果
*/
public int deleteJobLogByIds(Long[] logIds);
/**
* 删除任务日志
*
* @param jobId 调度日志ID
* @return 结果
*/
public int deleteJobLogById(Long jobId);
/**
* 清空任务日志
*/
public void cleanJobLog();
}

View File

@ -1,67 +0,0 @@
package com.ruoyi.quartz.mapper;
import java.util.List;
import com.ruoyi.quartz.domain.SysJob;
/**
* 调度任务信息 数据层
*
* @author ruoyi
*/
public interface SysJobMapper
{
/**
* 查询调度任务日志集合
*
* @param job 调度信息
* @return 操作日志集合
*/
public List<SysJob> selectJobList(SysJob job);
/**
* 查询所有调度任务
*
* @return 调度任务列表
*/
public List<SysJob> selectJobAll();
/**
* 通过调度ID查询调度任务信息
*
* @param jobId 调度ID
* @return 角色对象信息
*/
public SysJob selectJobById(Long jobId);
/**
* 通过调度ID删除调度任务信息
*
* @param jobId 调度ID
* @return 结果
*/
public int deleteJobById(Long jobId);
/**
* 批量删除调度任务信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteJobByIds(Long[] ids);
/**
* 修改调度任务信息
*
* @param job 调度任务信息
* @return 结果
*/
public int updateJob(SysJob job);
/**
* 新增调度任务信息
*
* @param job 调度任务信息
* @return 结果
*/
public int insertJob(SysJob job);
}

View File

@ -1,18 +1,18 @@
package com.ruoyi.quartz.service;
import java.util.List;
import com.ruoyi.quartz.domain.SysJobLog;
/**
* 定时任务调度日志信息信息 服务层
*
*
* @author ruoyi
*/
public interface ISysJobLogService
{
public interface ISysJobLogService {
/**
* 获取quartz调度器日志的计划任务
*
*
* @param jobLog 调度日志信息
* @return 调度任务日志集合
*/
@ -20,7 +20,7 @@ public interface ISysJobLogService
/**
* 通过调度任务日志ID查询调度信息
*
*
* @param jobLogId 调度任务日志ID
* @return 调度任务日志对象信息
*/
@ -28,14 +28,14 @@ public interface ISysJobLogService
/**
* 新增任务日志
*
*
* @param jobLog 调度日志信息
*/
public void addJobLog(SysJobLog jobLog);
/**
* 批量删除调度日志信息
*
*
* @param logIds 需要删除的日志ID
* @return 结果
*/
@ -43,7 +43,7 @@ public interface ISysJobLogService
/**
* 删除任务日志
*
*
* @param jobId 调度日志ID
* @return 结果
*/

View File

@ -1,20 +1,20 @@
package com.ruoyi.quartz.service;
import java.util.List;
import org.quartz.SchedulerException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
/**
* 定时任务调度信息信息 服务层
*
*
* @author ruoyi
*/
public interface ISysJobService
{
public interface ISysJobService {
/**
* 获取quartz调度器的计划任务
*
*
* @param job 调度信息
* @return 调度任务集合
*/
@ -22,7 +22,7 @@ public interface ISysJobService
/**
* 通过调度任务ID查询调度信息
*
*
* @param jobId 调度任务ID
* @return 调度任务对象信息
*/
@ -30,7 +30,7 @@ public interface ISysJobService
/**
* 暂停任务
*
*
* @param job 调度信息
* @return 结果
*/
@ -38,7 +38,7 @@ public interface ISysJobService
/**
* 恢复任务
*
*
* @param job 调度信息
* @return 结果
*/
@ -46,7 +46,7 @@ public interface ISysJobService
/**
* 删除任务后所对应的trigger也将被删除
*
*
* @param job 调度信息
* @return 结果
*/
@ -54,7 +54,7 @@ public interface ISysJobService
/**
* 批量删除调度信息
*
*
* @param jobIds 需要删除的任务ID
* @return 结果
*/
@ -62,7 +62,7 @@ public interface ISysJobService
/**
* 任务调度状态修改
*
*
* @param job 调度信息
* @return 结果
*/
@ -70,7 +70,7 @@ public interface ISysJobService
/**
* 立即运行任务
*
*
* @param job 调度信息
* @return 结果
*/
@ -78,7 +78,7 @@ public interface ISysJobService
/**
* 新增任务
*
*
* @param job 调度信息
* @return 结果
*/
@ -86,7 +86,7 @@ public interface ISysJobService
/**
* 更新任务
*
*
* @param job 调度信息
* @return 结果
*/
@ -94,7 +94,7 @@ public interface ISysJobService
/**
* 校验cron表达式是否有效
*
*
* @param cronExpression 表达式
* @return 结果
*/

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.quartz.domain.SysJobLog;
@ -9,70 +10,64 @@ import com.ruoyi.quartz.service.ISysJobLogService;
/**
* 定时任务调度日志信息 服务层
*
*
* @author ruoyi
*/
@Service
public class SysJobLogServiceImpl implements ISysJobLogService
{
public class SysJobLogServiceImpl implements ISysJobLogService {
@Autowired
private SysJobLogMapper jobLogMapper;
/**
* 获取quartz调度器日志的计划任务
*
*
* @param jobLog 调度日志信息
* @return 调度任务日志集合
*/
@Override
public List<SysJobLog> selectJobLogList(SysJobLog jobLog)
{
public List<SysJobLog> selectJobLogList(SysJobLog jobLog) {
return jobLogMapper.selectJobLogList(jobLog);
}
/**
* 通过调度任务日志ID查询调度信息
*
*
* @param jobLogId 调度任务日志ID
* @return 调度任务日志对象信息
*/
@Override
public SysJobLog selectJobLogById(Long jobLogId)
{
public SysJobLog selectJobLogById(Long jobLogId) {
return jobLogMapper.selectJobLogById(jobLogId);
}
/**
* 新增任务日志
*
*
* @param jobLog 调度日志信息
*/
@Override
public void addJobLog(SysJobLog jobLog)
{
public void addJobLog(SysJobLog jobLog) {
jobLogMapper.insertJobLog(jobLog);
}
/**
* 批量删除调度日志信息
*
*
* @param logIds 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteJobLogByIds(Long[] logIds)
{
public int deleteJobLogByIds(Long[] logIds) {
return jobLogMapper.deleteJobLogByIds(logIds);
}
/**
* 删除任务日志
*
*
* @param jobId 调度日志ID
*/
@Override
public int deleteJobLogById(Long jobId)
{
public int deleteJobLogById(Long jobId) {
return jobLogMapper.deleteJobLogById(jobId);
}
@ -80,8 +75,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService
* 清空任务日志
*/
@Override
public void cleanJobLog()
{
public void cleanJobLog() {
jobLogMapper.cleanJobLog();
}
}

View File

@ -2,6 +2,7 @@ package com.ruoyi.quartz.service.impl;
import java.util.List;
import javax.annotation.PostConstruct;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
@ -19,12 +20,11 @@ import com.ruoyi.quartz.util.ScheduleUtils;
/**
* 定时任务调度信息 服务层
*
*
* @author ruoyi
*/
@Service
public class SysJobServiceImpl implements ISysJobService
{
public class SysJobServiceImpl implements ISysJobService {
@Autowired
private Scheduler scheduler;
@ -35,55 +35,49 @@ public class SysJobServiceImpl implements ISysJobService
* 项目启动时初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理不能手动修改数据库ID和任务组名否则会导致脏数据
*/
@PostConstruct
public void init() throws SchedulerException, TaskException
{
public void init() throws SchedulerException, TaskException {
scheduler.clear();
List<SysJob> jobList = jobMapper.selectJobAll();
for (SysJob job : jobList)
{
for (SysJob job : jobList) {
ScheduleUtils.createScheduleJob(scheduler, job);
}
}
/**
* 获取quartz调度器的计划任务列表
*
*
* @param job 调度信息
* @return
*/
@Override
public List<SysJob> selectJobList(SysJob job)
{
public List<SysJob> selectJobList(SysJob job) {
return jobMapper.selectJobList(job);
}
/**
* 通过调度任务ID查询调度信息
*
*
* @param jobId 调度任务ID
* @return 调度任务对象信息
*/
@Override
public SysJob selectJobById(Long jobId)
{
public SysJob selectJobById(Long jobId) {
return jobMapper.selectJobById(jobId);
}
/**
* 暂停任务
*
*
* @param job 调度信息
*/
@Override
@Transactional
public int pauseJob(SysJob job) throws SchedulerException
{
public int pauseJob(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.updateJob(job);
if (rows > 0)
{
if (rows > 0) {
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
@ -91,19 +85,17 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 恢复任务
*
*
* @param job 调度信息
*/
@Override
@Transactional
public int resumeJob(SysJob job) throws SchedulerException
{
public int resumeJob(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
int rows = jobMapper.updateJob(job);
if (rows > 0)
{
if (rows > 0) {
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
@ -111,18 +103,16 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 删除任务后所对应的trigger也将被删除
*
*
* @param job 调度信息
*/
@Override
@Transactional
public int deleteJob(SysJob job) throws SchedulerException
{
public int deleteJob(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId);
if (rows > 0)
{
if (rows > 0) {
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
@ -130,16 +120,14 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 批量删除调度信息
*
*
* @param jobIds 需要删除的任务ID
* @return 结果
*/
@Override
@Transactional
public void deleteJobByIds(Long[] jobIds) throws SchedulerException
{
for (Long jobId : jobIds)
{
public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
for (Long jobId : jobIds) {
SysJob job = jobMapper.selectJobById(jobId);
deleteJob(job);
}
@ -147,21 +135,17 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 任务调度状态修改
*
*
* @param job 调度信息
*/
@Override
@Transactional
public int changeStatus(SysJob job) throws SchedulerException
{
public int changeStatus(SysJob job) throws SchedulerException {
int rows = 0;
String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status))
{
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
rows = resumeJob(job);
}
else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
{
} else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
rows = pauseJob(job);
}
return rows;
@ -169,13 +153,12 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 立即运行任务
*
*
* @param job 调度信息
*/
@Override
@Transactional
public void run(SysJob job) throws SchedulerException
{
public void run(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
SysJob properties = selectJobById(job.getJobId());
@ -187,17 +170,15 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 新增任务
*
*
* @param job 调度信息 调度信息
*/
@Override
@Transactional
public int insertJob(SysJob job) throws SchedulerException, TaskException
{
public int insertJob(SysJob job) throws SchedulerException, TaskException {
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.insertJob(job);
if (rows > 0)
{
if (rows > 0) {
ScheduleUtils.createScheduleJob(scheduler, job);
}
return rows;
@ -205,17 +186,15 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 更新任务的时间表达式
*
*
* @param job 调度信息
*/
@Override
@Transactional
public int updateJob(SysJob job) throws SchedulerException, TaskException
{
public int updateJob(SysJob job) throws SchedulerException, TaskException {
SysJob properties = selectJobById(job.getJobId());
int rows = jobMapper.updateJob(job);
if (rows > 0)
{
if (rows > 0) {
updateSchedulerJob(job, properties.getJobGroup());
}
return rows;
@ -223,17 +202,15 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 更新任务
*
* @param job 任务对象
*
* @param job 任务对象
* @param jobGroup 任务组名
*/
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException
{
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
Long jobId = job.getJobId();
// 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
if (scheduler.checkExists(jobKey))
{
if (scheduler.checkExists(jobKey)) {
// 防止创建时存在数据问题 先移除然后在执行创建操作
scheduler.deleteJob(jobKey);
}
@ -242,13 +219,12 @@ public class SysJobServiceImpl implements ISysJobService
/**
* 校验cron表达式是否有效
*
*
* @param cronExpression 表达式
* @return 结果
*/
@Override
public boolean checkCronExpressionIsValid(String cronExpression)
{
public boolean checkCronExpressionIsValid(String cronExpression) {
return CronUtils.isValid(cronExpression);
}
}

View File

@ -5,24 +5,20 @@ import com.ruoyi.common.utils.StringUtils;
/**
* 定时任务调度测试
*
*
* @author ruoyi
*/
@Component("ryTask")
public class RyTask
{
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
{
public class RyTask {
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
}
public void ryParams(String params)
{
public void ryParams(String params) {
System.out.println("执行有参方法:" + params);
}
public void ryNoParams()
{
public void ryNoParams() {
System.out.println("执行无参方法");
}
}

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.util;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
@ -21,8 +22,7 @@ import com.ruoyi.quartz.service.ISysJobLogService;
*
* @author ruoyi
*/
public abstract class AbstractQuartzJob implements Job
{
public abstract class AbstractQuartzJob implements Job {
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
/**
@ -31,21 +31,16 @@ public abstract class AbstractQuartzJob implements Job
private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
public void execute(JobExecutionContext context) throws JobExecutionException {
SysJob sysJob = new SysJob();
BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
try
{
try {
before(context, sysJob);
if (sysJob != null)
{
if (sysJob != null) {
doExecute(context, sysJob);
}
after(context, sysJob, null);
}
catch (Exception e)
{
} catch (Exception e) {
log.error("任务执行异常 - ", e);
after(context, sysJob, e);
}
@ -55,10 +50,9 @@ public abstract class AbstractQuartzJob implements Job
* 执行前
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param sysJob 系统计划任务
*/
protected void before(JobExecutionContext context, SysJob sysJob)
{
protected void before(JobExecutionContext context, SysJob sysJob) {
threadLocal.set(new Date());
}
@ -66,10 +60,9 @@ public abstract class AbstractQuartzJob implements Job
* 执行后
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param sysJob 系统计划任务
*/
protected void after(JobExecutionContext context, SysJob sysJob, Exception e)
{
protected void after(JobExecutionContext context, SysJob sysJob, Exception e) {
Date startTime = threadLocal.get();
threadLocal.remove();
@ -81,14 +74,11 @@ public abstract class AbstractQuartzJob implements Job
sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null)
{
if (e != null) {
sysJobLog.setStatus(Constants.FAIL);
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg);
}
else
{
} else {
sysJobLog.setStatus(Constants.SUCCESS);
}
@ -100,7 +90,7 @@ public abstract class AbstractQuartzJob implements Job
* 执行方法由子类重载
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param sysJob 系统计划任务
* @throws Exception 执行过程中的异常
*/
protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;

View File

@ -2,24 +2,22 @@ package com.ruoyi.quartz.util;
import java.text.ParseException;
import java.util.Date;
import org.quartz.CronExpression;
/**
* cron表达式工具类
*
* @author ruoyi
*
* @author ruoyi
*/
public class CronUtils
{
public class CronUtils {
/**
* 返回一个布尔值代表一个给定的Cron表达式的有效性
*
* @param cronExpression Cron表达式
* @return boolean 表达式是否有效
*/
public static boolean isValid(String cronExpression)
{
public static boolean isValid(String cronExpression) {
return CronExpression.isValidExpression(cronExpression);
}
@ -29,15 +27,11 @@ public class CronUtils
* @param cronExpression Cron表达式
* @return String 无效时返回表达式错误描述,如果有效返回null
*/
public static String getInvalidMessage(String cronExpression)
{
try
{
public static String getInvalidMessage(String cronExpression) {
try {
new CronExpression(cronExpression);
return null;
}
catch (ParseException pe)
{
} catch (ParseException pe) {
return pe.getMessage();
}
}
@ -48,15 +42,11 @@ public class CronUtils
* @param cronExpression Cron表达式
* @return Date 下次Cron表达式执行时间
*/
public static Date getNextExecution(String cronExpression)
{
try
{
public static Date getNextExecution(String cronExpression) {
try {
CronExpression cron = new CronExpression(cronExpression);
return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
}
catch (ParseException e)
{
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}

View File

@ -4,6 +4,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.quartz.domain.SysJob;
@ -13,27 +14,22 @@ import com.ruoyi.quartz.domain.SysJob;
*
* @author ruoyi
*/
public class JobInvokeUtil
{
public class JobInvokeUtil {
/**
* 执行方法
*
* @param sysJob 系统任务
*/
public static void invokeMethod(SysJob sysJob) throws Exception
{
public static void invokeMethod(SysJob sysJob) throws Exception {
String invokeTarget = sysJob.getInvokeTarget();
String beanName = getBeanName(invokeTarget);
String methodName = getMethodName(invokeTarget);
List<Object[]> methodParams = getMethodParams(invokeTarget);
if (!isValidClassName(beanName))
{
if (!isValidClassName(beanName)) {
Object bean = SpringUtils.getBean(beanName);
invokeMethod(bean, methodName, methodParams);
}
else
{
} else {
Object bean = Class.forName(beanName).newInstance();
invokeMethod(bean, methodName, methodParams);
}
@ -42,21 +38,17 @@ public class JobInvokeUtil
/**
* 调用任务方法
*
* @param bean 目标对象
* @param methodName 方法名称
* @param bean 目标对象
* @param methodName 方法名称
* @param methodParams 方法参数
*/
private static void invokeMethod(Object bean, String methodName, List<Object[]> methodParams)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0)
{
InvocationTargetException {
if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) {
Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams));
method.invoke(bean, getMethodParamsValue(methodParams));
}
else
{
} else {
Method method = bean.getClass().getDeclaredMethod(methodName);
method.invoke(bean);
}
@ -64,81 +56,70 @@ public class JobInvokeUtil
/**
* 校验是否为为class包名
*
*
* @param str 名称
* @return true是 false否
*/
public static boolean isValidClassName(String invokeTarget)
{
public static boolean isValidClassName(String invokeTarget) {
return StringUtils.countMatches(invokeTarget, ".") > 1;
}
/**
* 获取bean名称
*
*
* @param invokeTarget 目标字符串
* @return bean名称
*/
public static String getBeanName(String invokeTarget)
{
public static String getBeanName(String invokeTarget) {
String beanName = StringUtils.substringBefore(invokeTarget, "(");
return StringUtils.substringBeforeLast(beanName, ".");
}
/**
* 获取bean方法
*
*
* @param invokeTarget 目标字符串
* @return method方法
*/
public static String getMethodName(String invokeTarget)
{
public static String getMethodName(String invokeTarget) {
String methodName = StringUtils.substringBefore(invokeTarget, "(");
return StringUtils.substringAfterLast(methodName, ".");
}
/**
* 获取method方法参数相关列表
*
*
* @param invokeTarget 目标字符串
* @return method方法相关参数列表
*/
public static List<Object[]> getMethodParams(String invokeTarget)
{
public static List<Object[]> getMethodParams(String invokeTarget) {
String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")");
if (StringUtils.isEmpty(methodStr))
{
if (StringUtils.isEmpty(methodStr)) {
return null;
}
String[] methodParams = methodStr.split(",");
List<Object[]> classs = new LinkedList<>();
for (int i = 0; i < methodParams.length; i++)
{
for (int i = 0; i < methodParams.length; i++) {
String str = StringUtils.trimToEmpty(methodParams[i]);
// String字符串类型包含'
if (StringUtils.contains(str, "'"))
{
classs.add(new Object[] { StringUtils.replace(str, "'", ""), String.class });
if (StringUtils.contains(str, "'")) {
classs.add(new Object[]{StringUtils.replace(str, "'", ""), String.class});
}
// boolean布尔类型等于true或者false
else if (StringUtils.equals(str, "true") || StringUtils.equalsIgnoreCase(str, "false"))
{
classs.add(new Object[] { Boolean.valueOf(str), Boolean.class });
else if (StringUtils.equals(str, "true") || StringUtils.equalsIgnoreCase(str, "false")) {
classs.add(new Object[]{Boolean.valueOf(str), Boolean.class});
}
// long长整形包含L
else if (StringUtils.containsIgnoreCase(str, "L"))
{
classs.add(new Object[] { Long.valueOf(StringUtils.replaceIgnoreCase(str, "L", "")), Long.class });
else if (StringUtils.containsIgnoreCase(str, "L")) {
classs.add(new Object[]{Long.valueOf(StringUtils.replaceIgnoreCase(str, "L", "")), Long.class});
}
// double浮点类型包含D
else if (StringUtils.containsIgnoreCase(str, "D"))
{
classs.add(new Object[] { Double.valueOf(StringUtils.replaceIgnoreCase(str, "D", "")), Double.class });
else if (StringUtils.containsIgnoreCase(str, "D")) {
classs.add(new Object[]{Double.valueOf(StringUtils.replaceIgnoreCase(str, "D", "")), Double.class});
}
// 其他类型归类为整形
else
{
classs.add(new Object[] { Integer.valueOf(str), Integer.class });
else {
classs.add(new Object[]{Integer.valueOf(str), Integer.class});
}
}
return classs;
@ -146,16 +127,14 @@ public class JobInvokeUtil
/**
* 获取参数类型
*
*
* @param methodParams 参数相关列表
* @return 参数类型列表
*/
public static Class<?>[] getMethodParamsType(List<Object[]> methodParams)
{
public static Class<?>[] getMethodParamsType(List<Object[]> methodParams) {
Class<?>[] classs = new Class<?>[methodParams.size()];
int index = 0;
for (Object[] os : methodParams)
{
for (Object[] os : methodParams) {
classs[index] = (Class<?>) os[1];
index++;
}
@ -164,16 +143,14 @@ public class JobInvokeUtil
/**
* 获取参数值
*
*
* @param methodParams 参数相关列表
* @return 参数值列表
*/
public static Object[] getMethodParamsValue(List<Object[]> methodParams)
{
public static Object[] getMethodParamsValue(List<Object[]> methodParams) {
Object[] classs = new Object[methodParams.size()];
int index = 0;
for (Object[] os : methodParams)
{
for (Object[] os : methodParams) {
classs[index] = (Object) os[0];
index++;
}

View File

@ -6,16 +6,13 @@ import com.ruoyi.quartz.domain.SysJob;
/**
* 定时任务处理禁止并发执行
*
* @author ruoyi
*
* @author ruoyi
*/
@DisallowConcurrentExecution
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob
{
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception
{
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
}
}

View File

@ -5,15 +5,12 @@ import com.ruoyi.quartz.domain.SysJob;
/**
* 定时任务处理允许并发执行
*
* @author ruoyi
*
* @author ruoyi
*/
public class QuartzJobExecution extends AbstractQuartzJob
{
public class QuartzJobExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception
{
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
}
}

View File

@ -17,20 +17,17 @@ import com.ruoyi.quartz.domain.SysJob;
/**
* 定时任务工具类
*
* @author ruoyi
*
* @author ruoyi
*/
public class ScheduleUtils
{
public class ScheduleUtils {
/**
* 得到quartz任务类
*
* @param sysJob 执行计划
* @return 具体执行任务类
*/
private static Class<? extends Job> getQuartzJobClass(SysJob sysJob)
{
private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) {
boolean isConcurrent = "0".equals(sysJob.getConcurrent());
return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
}
@ -38,24 +35,21 @@ public class ScheduleUtils
/**
* 构建任务触发对象
*/
public static TriggerKey getTriggerKey(Long jobId, String jobGroup)
{
public static TriggerKey getTriggerKey(Long jobId, String jobGroup) {
return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
}
/**
* 构建任务键对象
*/
public static JobKey getJobKey(Long jobId, String jobGroup)
{
public static JobKey getJobKey(Long jobId, String jobGroup) {
return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
}
/**
* 创建定时任务
*/
public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException
{
public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {
Class<? extends Job> jobClass = getQuartzJobClass(job);
// 构建job信息
Long jobId = job.getJobId();
@ -74,8 +68,7 @@ public class ScheduleUtils
jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);
// 判断是否存在
if (scheduler.checkExists(getJobKey(jobId, jobGroup)))
{
if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
// 防止创建时存在数据问题 先移除然后在执行创建操作
scheduler.deleteJob(getJobKey(jobId, jobGroup));
}
@ -83,8 +76,7 @@ public class ScheduleUtils
scheduler.scheduleJob(jobDetail, trigger);
// 暂停任务
if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue()))
{
if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
}
@ -93,10 +85,8 @@ public class ScheduleUtils
* 设置定时任务策略
*/
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
throws TaskException
{
switch (job.getMisfirePolicy())
{
throws TaskException {
switch (job.getMisfirePolicy()) {
case ScheduleConstants.MISFIRE_DEFAULT:
return cb;
case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:

View File

@ -1,93 +0,0 @@
<?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.ruoyi.quartz.mapper.SysJobLogMapper">
<resultMap type="SysJobLog" id="SysJobLogResult">
<id property="jobLogId" column="job_log_id" />
<result property="jobName" column="job_name" />
<result property="jobGroup" column="job_group" />
<result property="invokeTarget" column="invoke_target" />
<result property="jobMessage" column="job_message" />
<result property="status" column="status" />
<result property="exceptionInfo" column="exception_info" />
<result property="createTime" column="create_time" />
</resultMap>
<sql id="selectJobLogVo">
select job_log_id, job_name, job_group, invoke_target, job_message, status, exception_info, create_time
from sys_job_log
</sql>
<select id="selectJobLogList" parameterType="SysJobLog" resultMap="SysJobLogResult">
<include refid="selectJobLogVo"/>
<where>
<if test="jobName != null and jobName != ''">
AND job_name like concat('%', #{jobName}, '%')
</if>
<if test="jobGroup != null and jobGroup != ''">
AND job_group = #{jobGroup}
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="invokeTarget != null and invokeTarget != ''">
AND invoke_target like concat('%', #{invokeTarget}, '%')
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
and date_format(create_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
and date_format(create_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
</where>
</select>
<select id="selectJobLogAll" resultMap="SysJobLogResult">
<include refid="selectJobLogVo"/>
</select>
<select id="selectJobLogById" parameterType="Long" resultMap="SysJobLogResult">
<include refid="selectJobLogVo"/>
where job_log_id = #{jobLogId}
</select>
<delete id="deleteJobLogById" parameterType="Long">
delete from sys_job_log where job_log_id = #{jobLogId}
</delete>
<delete id="deleteJobLogByIds" parameterType="Long">
delete from sys_job_log where job_log_id in
<foreach collection="array" item="jobLogId" open="(" separator="," close=")">
#{jobLogId}
</foreach>
</delete>
<update id="cleanJobLog">
truncate table sys_job_log
</update>
<insert id="insertJobLog" parameterType="SysJobLog">
insert into sys_job_log(
<if test="jobLogId != null and jobLogId != 0">job_log_id,</if>
<if test="jobName != null and jobName != ''">job_name,</if>
<if test="jobGroup != null and jobGroup != ''">job_group,</if>
<if test="invokeTarget != null and invokeTarget != ''">invoke_target,</if>
<if test="jobMessage != null and jobMessage != ''">job_message,</if>
<if test="status != null and status != ''">status,</if>
<if test="exceptionInfo != null and exceptionInfo != ''">exception_info,</if>
create_time
)values(
<if test="jobLogId != null and jobLogId != 0">#{jobLogId},</if>
<if test="jobName != null and jobName != ''">#{jobName},</if>
<if test="jobGroup != null and jobGroup != ''">#{jobGroup},</if>
<if test="invokeTarget != null and invokeTarget != ''">#{invokeTarget},</if>
<if test="jobMessage != null and jobMessage != ''">#{jobMessage},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="exceptionInfo != null and exceptionInfo != ''">#{exceptionInfo},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1,111 +0,0 @@
<?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.ruoyi.quartz.mapper.SysJobMapper">
<resultMap type="SysJob" id="SysJobResult">
<id property="jobId" column="job_id" />
<result property="jobName" column="job_name" />
<result property="jobGroup" column="job_group" />
<result property="invokeTarget" column="invoke_target" />
<result property="cronExpression" column="cron_expression" />
<result property="misfirePolicy" column="misfire_policy" />
<result property="concurrent" column="concurrent" />
<result property="status" column="status" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
</resultMap>
<sql id="selectJobVo">
select job_id, job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, status, create_by, create_time, remark
from sys_job
</sql>
<select id="selectJobList" parameterType="SysJob" resultMap="SysJobResult">
<include refid="selectJobVo"/>
<where>
<if test="jobName != null and jobName != ''">
AND job_name like concat('%', #{jobName}, '%')
</if>
<if test="jobGroup != null and jobGroup != ''">
AND job_group = #{jobGroup}
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="invokeTarget != null and invokeTarget != ''">
AND invoke_target like concat('%', #{invokeTarget}, '%')
</if>
</where>
</select>
<select id="selectJobAll" resultMap="SysJobResult">
<include refid="selectJobVo"/>
</select>
<select id="selectJobById" parameterType="Long" resultMap="SysJobResult">
<include refid="selectJobVo"/>
where job_id = #{jobId}
</select>
<delete id="deleteJobById" parameterType="Long">
delete from sys_job where job_id = #{jobId}
</delete>
<delete id="deleteJobByIds" parameterType="Long">
delete from sys_job where job_id in
<foreach collection="array" item="jobId" open="(" separator="," close=")">
#{jobId}
</foreach>
</delete>
<update id="updateJob" parameterType="SysJob">
update sys_job
<set>
<if test="jobName != null and jobName != ''">job_name = #{jobName},</if>
<if test="jobGroup != null and jobGroup != ''">job_group = #{jobGroup},</if>
<if test="invokeTarget != null and invokeTarget != ''">invoke_target = #{invokeTarget},</if>
<if test="cronExpression != null and cronExpression != ''">cron_expression = #{cronExpression},</if>
<if test="misfirePolicy != null and misfirePolicy != ''">misfire_policy = #{misfirePolicy},</if>
<if test="concurrent != null and concurrent != ''">concurrent = #{concurrent},</if>
<if test="status !=null">status = #{status},</if>
<if test="remark != null and remark != ''">remark = #{remark},</if>
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
update_time = sysdate()
</set>
where job_id = #{jobId}
</update>
<insert id="insertJob" parameterType="SysJob" useGeneratedKeys="true" keyProperty="jobId">
insert into sys_job(
<if test="jobId != null and jobId != 0">job_id,</if>
<if test="jobName != null and jobName != ''">job_name,</if>
<if test="jobGroup != null and jobGroup != ''">job_group,</if>
<if test="invokeTarget != null and invokeTarget != ''">invoke_target,</if>
<if test="cronExpression != null and cronExpression != ''">cron_expression,</if>
<if test="misfirePolicy != null and misfirePolicy != ''">misfire_policy,</if>
<if test="concurrent != null and concurrent != ''">concurrent,</if>
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
create_time
)values(
<if test="jobId != null and jobId != 0">#{jobId},</if>
<if test="jobName != null and jobName != ''">#{jobName},</if>
<if test="jobGroup != null and jobGroup != ''">#{jobGroup},</if>
<if test="invokeTarget != null and invokeTarget != ''">#{invokeTarget},</if>
<if test="cronExpression != null and cronExpression != ''">#{cronExpression},</if>
<if test="misfirePolicy != null and misfirePolicy != ''">#{misfirePolicy},</if>
<if test="concurrent != null and concurrent != ''">#{concurrent},</if>
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
sysdate()
)
</insert>
</mapper>

View File

@ -1 +0,0 @@
package cn.iocoder.dashboard.modules.infra.controller;

View File

@ -0,0 +1,97 @@
package cn.iocoder.dashboard.modules.infra.dal.dataobject.job;
import cn.iocoder.dashboard.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.dashboard.modules.infra.enums.job.InfJobStatusEnum;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.Date;
/**
* 定时任务表
*
* @author 芋道源码
*/
@TableName("inf_job")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfJob extends BaseDO {
/**
* 任务编号
*/
@TableId
private Long id;
/**
* 任务名称
*/
private String name;
/**
* 任务分组
*/
@TableField("`group`")
private String group;
/**
* 任务状态
*
* 枚举 {@link InfJobStatusEnum}
*/
private Integer status;
/**
* 处理器的名字
*/
private String handlerName;
/**
* 处理器的参数
*/
private String handlerParam;
// ========== 时间相关字段 ==========
/**
* CRON 表达式
*/
private String cronExpression;
/**
* 最后一次执行的开始时间
*
* 该字段在任务执行结束后进行记录
*/
private Date executeBeginTime;
/**
* 最后一次执行的结束时间
*
* 该字段在任务执行结束后进行记录
*/
private Date executeEndTime;
/**
* 上一次触发时间来自 Quartz SCHE_TRIGGERS
*/
private Date firePrevTime;
/**
* 下一次触发时间来自 Quartz SCHE_TRIGGERS
*
* 在触发器状态从 `ACQUIRED` 变成 `BLOCKED` 就会更新 PREV_FIRE_TIMENEXT_FIRE_TIME然后定时任务才正式开始执行
*/
private Date fireNextTime;
// ========== 监控相关字段 ==========
/**
* 监控开关
*/
private Boolean monitorSwitch;
/**
* 监控超时时间单位毫秒
*/
private Integer monitorTimeout;
// TODO misfirePolicy
// TODO concurrent
// TODO 失败重试
}

View File

@ -0,0 +1,89 @@
package cn.iocoder.dashboard.modules.infra.dal.dataobject.job;
import cn.iocoder.dashboard.common.pojo.CommonResult;
import cn.iocoder.dashboard.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.Date;
/**
* 定时任务的执行日志 sys_job_log
*
* @author 芋道源码
*/
@TableName("inf_job_log")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class InfJobLog extends BaseDO {
/**
* 日志编号
*/
private Long id;
/**
* 任务编号
*
* 关联 {@link InfJob#getId()}
*/
private Long jobId;
/**
* 任务名称
*
* 冗余字段 {@link InfJob#getName()}
*/
private String jobName;
/**
* 任务分组
*
* 冗余字段 {@link InfJob#getGroup()}
*/
private String jobGroup;
/**
* 处理器的名字
*
* 冗余字段 {@link InfJob#getHandlerName()}
*/
private String handlerName;
/**
* 处理器的参数
*
* 冗余字段 {@link InfJob#getHandlerParam()}
*/
private String handlerParam;
/**
* 开始执行时间
*/
private Date startTime;
/**
* 结束执行时间
*/
private Date endTime;
/**
* 执行时长单位毫秒
*/
private Integer duration;
/**
* 结果码
*
* 目前使用的 {@link CommonResult#getCode()} 属性
*/
private Integer resultCode;
/**
* 结果提示
*
* 目前使用的 {@link CommonResult#getMsg()} 属性
*/
private String resultMsg;
/**
* 结果数据
*
* 如果是对象则使用 JSON 格式化
*/
private String resultData;
}

View File

@ -1 +0,0 @@
package cn.iocoder.dashboard.modules.infra.dal.dataobject;

View File

@ -0,0 +1,47 @@
package cn.iocoder.dashboard.modules.infra.enums.job;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Collections;
import java.util.Set;
import static org.quartz.impl.jdbcjobstore.Constants.*;
/**
* 任务状态的枚举
*
* @author 芋道源码
*/
@Getter
@AllArgsConstructor
public enum InfJobStatusEnum {
/**
* 初始化中
*/
INIT(0, Collections.emptySet()),
/**
* 开启运行
*/
NORMAL(1, Sets.newHashSet(STATE_WAITING, STATE_ACQUIRED, STATE_BLOCKED)),
/**
* 异常运行
*/
EXCEPTION(2, Sets.newHashSet(STATE_COMPLETE)),
/**
* 暂停运行
*/
STOP(3, Sets.newHashSet(STATE_PAUSED, STATE_PAUSED_BLOCKED));
/**
* 状态
*/
private final Integer status;
/**
* 对应的 Quartz 触发器的状态集合
*/
private final Set<String> quartzStates;
}