初始化 quartz 模块~

pull/2/head
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> <version>1.7.0</version>
</dependency> </dependency>
<!-- Job 定时任务相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!-- 监控相关 --> <!-- 监控相关 -->
<dependency> <dependency>
<groupId>org.apache.skywalking</groupId> <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 * @author ruoyi
*/ */
public class ScheduleConstants public class ScheduleConstants {
{
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */ /**
* key
*/
public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */ /**
*
*/
public static final String MISFIRE_DEFAULT = "0"; public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */ /**
*
*/
public static final String MISFIRE_IGNORE_MISFIRES = "1"; public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */ /**
*
*/
public static final String MISFIRE_FIRE_AND_PROCEED = "2"; public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */ /**
*
*/
public static final String MISFIRE_DO_NOTHING = "3"; 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 String value;
private Status(String value) private Status(String value) {
{
this.value = value; this.value = value;
} }
public String getValue() public String getValue() {
{
return value; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.util.Properties; import java.util.Properties;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Configuration @Configuration
public class ScheduleConfig public class ScheduleConfig {
{
@Bean @Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
{
SchedulerFactoryBean factory = new SchedulerFactoryBean(); SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource); factory.setDataSource(dataSource);

View File

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

View File

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

View File

@ -1,20 +1,20 @@
package com.ruoyi.quartz.service; package com.ruoyi.quartz.service;
import java.util.List; import java.util.List;
import org.quartz.SchedulerException; import org.quartz.SchedulerException;
import com.ruoyi.common.exception.job.TaskException; import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob; import com.ruoyi.quartz.domain.SysJob;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
public interface ISysJobService public interface ISysJobService {
{
/** /**
* quartz * quartz
* *
* @param job * @param job
* @return * @return
*/ */
@ -22,7 +22,7 @@ public interface ISysJobService
/** /**
* ID * ID
* *
* @param jobId ID * @param jobId ID
* @return * @return
*/ */
@ -30,7 +30,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -38,7 +38,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -46,7 +46,7 @@ public interface ISysJobService
/** /**
* trigger * trigger
* *
* @param job * @param job
* @return * @return
*/ */
@ -54,7 +54,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param jobIds ID * @param jobIds ID
* @return * @return
*/ */
@ -62,7 +62,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -70,7 +70,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -78,7 +78,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -86,7 +86,7 @@ public interface ISysJobService
/** /**
* *
* *
* @param job * @param job
* @return * @return
*/ */
@ -94,7 +94,7 @@ public interface ISysJobService
/** /**
* cron * cron
* *
* @param cronExpression * @param cronExpression
* @return * @return
*/ */

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.service.impl; package com.ruoyi.quartz.service.impl;
import java.util.List; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.ruoyi.quartz.domain.SysJobLog; import com.ruoyi.quartz.domain.SysJobLog;
@ -9,70 +10,64 @@ import com.ruoyi.quartz.service.ISysJobLogService;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysJobLogServiceImpl implements ISysJobLogService public class SysJobLogServiceImpl implements ISysJobLogService {
{
@Autowired @Autowired
private SysJobLogMapper jobLogMapper; private SysJobLogMapper jobLogMapper;
/** /**
* quartz * quartz
* *
* @param jobLog * @param jobLog
* @return * @return
*/ */
@Override @Override
public List<SysJobLog> selectJobLogList(SysJobLog jobLog) public List<SysJobLog> selectJobLogList(SysJobLog jobLog) {
{
return jobLogMapper.selectJobLogList(jobLog); return jobLogMapper.selectJobLogList(jobLog);
} }
/** /**
* ID * ID
* *
* @param jobLogId ID * @param jobLogId ID
* @return * @return
*/ */
@Override @Override
public SysJobLog selectJobLogById(Long jobLogId) public SysJobLog selectJobLogById(Long jobLogId) {
{
return jobLogMapper.selectJobLogById(jobLogId); return jobLogMapper.selectJobLogById(jobLogId);
} }
/** /**
* *
* *
* @param jobLog * @param jobLog
*/ */
@Override @Override
public void addJobLog(SysJobLog jobLog) public void addJobLog(SysJobLog jobLog) {
{
jobLogMapper.insertJobLog(jobLog); jobLogMapper.insertJobLog(jobLog);
} }
/** /**
* *
* *
* @param logIds ID * @param logIds ID
* @return * @return
*/ */
@Override @Override
public int deleteJobLogByIds(Long[] logIds) public int deleteJobLogByIds(Long[] logIds) {
{
return jobLogMapper.deleteJobLogByIds(logIds); return jobLogMapper.deleteJobLogByIds(logIds);
} }
/** /**
* *
* *
* @param jobId ID * @param jobId ID
*/ */
@Override @Override
public int deleteJobLogById(Long jobId) public int deleteJobLogById(Long jobId) {
{
return jobLogMapper.deleteJobLogById(jobId); return jobLogMapper.deleteJobLogById(jobId);
} }
@ -80,8 +75,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService
* *
*/ */
@Override @Override
public void cleanJobLog() public void cleanJobLog() {
{
jobLogMapper.cleanJobLog(); jobLogMapper.cleanJobLog();
} }
} }

View File

@ -2,6 +2,7 @@ package com.ruoyi.quartz.service.impl;
import java.util.List; import java.util.List;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import org.quartz.JobDataMap; import org.quartz.JobDataMap;
import org.quartz.JobKey; import org.quartz.JobKey;
import org.quartz.Scheduler; import org.quartz.Scheduler;
@ -19,12 +20,11 @@ import com.ruoyi.quartz.util.ScheduleUtils;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@Service @Service
public class SysJobServiceImpl implements ISysJobService public class SysJobServiceImpl implements ISysJobService {
{
@Autowired @Autowired
private Scheduler scheduler; private Scheduler scheduler;
@ -35,55 +35,49 @@ public class SysJobServiceImpl implements ISysJobService
* ID * ID
*/ */
@PostConstruct @PostConstruct
public void init() throws SchedulerException, TaskException public void init() throws SchedulerException, TaskException {
{
scheduler.clear(); scheduler.clear();
List<SysJob> jobList = jobMapper.selectJobAll(); List<SysJob> jobList = jobMapper.selectJobAll();
for (SysJob job : jobList) for (SysJob job : jobList) {
{
ScheduleUtils.createScheduleJob(scheduler, job); ScheduleUtils.createScheduleJob(scheduler, job);
} }
} }
/** /**
* quartz * quartz
* *
* @param job * @param job
* @return * @return
*/ */
@Override @Override
public List<SysJob> selectJobList(SysJob job) public List<SysJob> selectJobList(SysJob job) {
{
return jobMapper.selectJobList(job); return jobMapper.selectJobList(job);
} }
/** /**
* ID * ID
* *
* @param jobId ID * @param jobId ID
* @return * @return
*/ */
@Override @Override
public SysJob selectJobById(Long jobId) public SysJob selectJobById(Long jobId) {
{
return jobMapper.selectJobById(jobId); return jobMapper.selectJobById(jobId);
} }
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int pauseJob(SysJob job) throws SchedulerException public int pauseJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.updateJob(job); int rows = jobMapper.updateJob(job);
if (rows > 0) if (rows > 0) {
{
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
} }
return rows; return rows;
@ -91,19 +85,17 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int resumeJob(SysJob job) throws SchedulerException public int resumeJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
int rows = jobMapper.updateJob(job); int rows = jobMapper.updateJob(job);
if (rows > 0) if (rows > 0) {
{
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup)); scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
} }
return rows; return rows;
@ -111,18 +103,16 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* trigger * trigger
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int deleteJob(SysJob job) throws SchedulerException public int deleteJob(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId); int rows = jobMapper.deleteJobById(jobId);
if (rows > 0) if (rows > 0) {
{
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
} }
return rows; return rows;
@ -130,16 +120,14 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param jobIds ID * @param jobIds ID
* @return * @return
*/ */
@Override @Override
@Transactional @Transactional
public void deleteJobByIds(Long[] jobIds) throws SchedulerException public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
{ for (Long jobId : jobIds) {
for (Long jobId : jobIds)
{
SysJob job = jobMapper.selectJobById(jobId); SysJob job = jobMapper.selectJobById(jobId);
deleteJob(job); deleteJob(job);
} }
@ -147,21 +135,17 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int changeStatus(SysJob job) throws SchedulerException public int changeStatus(SysJob job) throws SchedulerException {
{
int rows = 0; int rows = 0;
String status = job.getStatus(); String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
{
rows = resumeJob(job); rows = resumeJob(job);
} } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
else if (ScheduleConstants.Status.PAUSE.getValue().equals(status))
{
rows = pauseJob(job); rows = pauseJob(job);
} }
return rows; return rows;
@ -169,13 +153,12 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public void run(SysJob job) throws SchedulerException public void run(SysJob job) throws SchedulerException {
{
Long jobId = job.getJobId(); Long jobId = job.getJobId();
String jobGroup = job.getJobGroup(); String jobGroup = job.getJobGroup();
SysJob properties = selectJobById(job.getJobId()); SysJob properties = selectJobById(job.getJobId());
@ -187,17 +170,15 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int insertJob(SysJob job) throws SchedulerException, TaskException public int insertJob(SysJob job) throws SchedulerException, TaskException {
{
job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.insertJob(job); int rows = jobMapper.insertJob(job);
if (rows > 0) if (rows > 0) {
{
ScheduleUtils.createScheduleJob(scheduler, job); ScheduleUtils.createScheduleJob(scheduler, job);
} }
return rows; return rows;
@ -205,17 +186,15 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
*/ */
@Override @Override
@Transactional @Transactional
public int updateJob(SysJob job) throws SchedulerException, TaskException public int updateJob(SysJob job) throws SchedulerException, TaskException {
{
SysJob properties = selectJobById(job.getJobId()); SysJob properties = selectJobById(job.getJobId());
int rows = jobMapper.updateJob(job); int rows = jobMapper.updateJob(job);
if (rows > 0) if (rows > 0) {
{
updateSchedulerJob(job, properties.getJobGroup()); updateSchedulerJob(job, properties.getJobGroup());
} }
return rows; return rows;
@ -223,17 +202,15 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* *
* *
* @param job * @param job
* @param jobGroup * @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(); Long jobId = job.getJobId();
// 判断是否存在 // 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup); JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
if (scheduler.checkExists(jobKey)) if (scheduler.checkExists(jobKey)) {
{
// 防止创建时存在数据问题 先移除,然后在执行创建操作 // 防止创建时存在数据问题 先移除,然后在执行创建操作
scheduler.deleteJob(jobKey); scheduler.deleteJob(jobKey);
} }
@ -242,13 +219,12 @@ public class SysJobServiceImpl implements ISysJobService
/** /**
* cron * cron
* *
* @param cronExpression * @param cronExpression
* @return * @return
*/ */
@Override @Override
public boolean checkCronExpressionIsValid(String cronExpression) public boolean checkCronExpressionIsValid(String cronExpression) {
{
return CronUtils.isValid(cronExpression); return CronUtils.isValid(cronExpression);
} }
} }

View File

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

View File

@ -1,6 +1,7 @@
package com.ruoyi.quartz.util; package com.ruoyi.quartz.util;
import java.util.Date; import java.util.Date;
import org.quartz.Job; import org.quartz.Job;
import org.quartz.JobExecutionContext; import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException; import org.quartz.JobExecutionException;
@ -21,8 +22,7 @@ import com.ruoyi.quartz.service.ISysJobLogService;
* *
* @author ruoyi * @author ruoyi
*/ */
public abstract class AbstractQuartzJob implements Job public abstract class AbstractQuartzJob implements Job {
{
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); 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<>(); private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
@Override @Override
public void execute(JobExecutionContext context) throws JobExecutionException public void execute(JobExecutionContext context) throws JobExecutionException {
{
SysJob sysJob = new SysJob(); SysJob sysJob = new SysJob();
BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
try try {
{
before(context, sysJob); before(context, sysJob);
if (sysJob != null) if (sysJob != null) {
{
doExecute(context, sysJob); doExecute(context, sysJob);
} }
after(context, sysJob, null); after(context, sysJob, null);
} } catch (Exception e) {
catch (Exception e)
{
log.error("任务执行异常 - ", e); log.error("任务执行异常 - ", e);
after(context, sysJob, e); after(context, sysJob, e);
} }
@ -55,10 +50,9 @@ public abstract class AbstractQuartzJob implements Job
* *
* *
* @param context * @param context
* @param sysJob * @param sysJob
*/ */
protected void before(JobExecutionContext context, SysJob sysJob) protected void before(JobExecutionContext context, SysJob sysJob) {
{
threadLocal.set(new Date()); threadLocal.set(new Date());
} }
@ -66,10 +60,9 @@ public abstract class AbstractQuartzJob implements Job
* *
* *
* @param context * @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(); Date startTime = threadLocal.get();
threadLocal.remove(); threadLocal.remove();
@ -81,14 +74,11 @@ public abstract class AbstractQuartzJob implements Job
sysJobLog.setStopTime(new Date()); sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime(); long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null) if (e != null) {
{
sysJobLog.setStatus(Constants.FAIL); sysJobLog.setStatus(Constants.FAIL);
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg); sysJobLog.setExceptionInfo(errorMsg);
} } else {
else
{
sysJobLog.setStatus(Constants.SUCCESS); sysJobLog.setStatus(Constants.SUCCESS);
} }
@ -100,7 +90,7 @@ public abstract class AbstractQuartzJob implements Job
* *
* *
* @param context * @param context
* @param sysJob * @param sysJob
* @throws Exception * @throws Exception
*/ */
protected abstract void doExecute(JobExecutionContext context, SysJob 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.text.ParseException;
import java.util.Date; import java.util.Date;
import org.quartz.CronExpression; import org.quartz.CronExpression;
/** /**
* cron * cron
*
* @author ruoyi
* *
* @author ruoyi
*/ */
public class CronUtils public class CronUtils {
{
/** /**
* Cron * Cron
* *
* @param cronExpression Cron * @param cronExpression Cron
* @return boolean * @return boolean
*/ */
public static boolean isValid(String cronExpression) public static boolean isValid(String cronExpression) {
{
return CronExpression.isValidExpression(cronExpression); return CronExpression.isValidExpression(cronExpression);
} }
@ -29,15 +27,11 @@ public class CronUtils
* @param cronExpression Cron * @param cronExpression Cron
* @return String ,null * @return String ,null
*/ */
public static String getInvalidMessage(String cronExpression) public static String getInvalidMessage(String cronExpression) {
{ try {
try
{
new CronExpression(cronExpression); new CronExpression(cronExpression);
return null; return null;
} } catch (ParseException pe) {
catch (ParseException pe)
{
return pe.getMessage(); return pe.getMessage();
} }
} }
@ -48,15 +42,11 @@ public class CronUtils
* @param cronExpression Cron * @param cronExpression Cron
* @return Date Cron * @return Date Cron
*/ */
public static Date getNextExecution(String cronExpression) public static Date getNextExecution(String cronExpression) {
{ try {
try
{
CronExpression cron = new CronExpression(cronExpression); CronExpression cron = new CronExpression(cronExpression);
return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
} } catch (ParseException e) {
catch (ParseException e)
{
throw new IllegalArgumentException(e.getMessage()); throw new IllegalArgumentException(e.getMessage());
} }
} }

View File

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

View File

@ -6,16 +6,13 @@ import com.ruoyi.quartz.domain.SysJob;
/** /**
* *
*
* @author ruoyi
* *
* @author ruoyi
*/ */
@DisallowConcurrentExecution @DisallowConcurrentExecution
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob {
{
@Override @Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
{
JobInvokeUtil.invokeMethod(sysJob); 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 @Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
{
JobInvokeUtil.invokeMethod(sysJob); 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 * quartz
* *
* @param sysJob * @param sysJob
* @return * @return
*/ */
private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) {
{
boolean isConcurrent = "0".equals(sysJob.getConcurrent()); boolean isConcurrent = "0".equals(sysJob.getConcurrent());
return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class; 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); 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); 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); Class<? extends Job> jobClass = getQuartzJobClass(job);
// 构建job信息 // 构建job信息
Long jobId = job.getJobId(); Long jobId = job.getJobId();
@ -74,8 +68,7 @@ public class ScheduleUtils
jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);
// 判断是否存在 // 判断是否存在
if (scheduler.checkExists(getJobKey(jobId, jobGroup))) if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
{
// 防止创建时存在数据问题 先移除,然后在执行创建操作 // 防止创建时存在数据问题 先移除,然后在执行创建操作
scheduler.deleteJob(getJobKey(jobId, jobGroup)); scheduler.deleteJob(getJobKey(jobId, jobGroup));
} }
@ -83,8 +76,7 @@ public class ScheduleUtils
scheduler.scheduleJob(jobDetail, trigger); 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)); scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
} }
} }
@ -93,10 +85,8 @@ public class ScheduleUtils
* *
*/ */
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
throws TaskException throws TaskException {
{ switch (job.getMisfirePolicy()) {
switch (job.getMisfirePolicy())
{
case ScheduleConstants.MISFIRE_DEFAULT: case ScheduleConstants.MISFIRE_DEFAULT:
return cb; return cb;
case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: 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;
}