1. 完成 Job 的 CRUD 功能

pull/2/head
YunaiV 2021-02-14 23:01:21 +08:00
parent bc1504d991
commit f60855faa0
27 changed files with 1277 additions and 1374 deletions

View File

@ -61,25 +61,4 @@ public class SysJobLogController extends BaseController {
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "定时任务调度日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobLogIds}")
public AjaxResult remove(@PathVariable Long[] jobLogIds) {
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "调度日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean() {
jobLogService.cleanJobLog();
return AjaxResult.success();
}
}

View File

@ -15,6 +15,7 @@ import com.ruoyi.quartz.service.ISysJobLogService;
*/
@Service
public class SysJobLogServiceImpl implements ISysJobLogService {
@Autowired
private SysJobLogMapper jobLogMapper;
@ -50,32 +51,4 @@ public class SysJobLogServiceImpl implements ISysJobLogService {
jobLogMapper.insertJobLog(jobLog);
}
/**
*
*
* @param logIds ID
* @return
*/
@Override
public int deleteJobLogByIds(Long[] logIds) {
return jobLogMapper.deleteJobLogByIds(logIds);
}
/**
*
*
* @param jobId ID
*/
@Override
public int deleteJobLogById(Long jobId) {
return jobLogMapper.deleteJobLogById(jobId);
}
/**
*
*/
@Override
public void cleanJobLog() {
jobLogMapper.cleanJobLog();
}
}

View File

@ -1,132 +0,0 @@
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;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/job")
public class SysJobController extends BaseController {
@Autowired
private ISysJobService jobService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:list')")
@GetMapping("/list")
public TableDataInfo list(SysJob sysJob) {
startPage();
List<SysJob> list = jobService.selectJobList(sysJob);
return getDataTable(list);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:export')")
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJob sysJob) {
List<SysJob> list = jobService.selectJobList(sysJob);
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
return util.exportExcel(list, "定时任务");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:query')")
@GetMapping(value = "/{jobId}")
public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
return AjaxResult.success(jobService.selectJobById(jobId));
}
/**
*
*/
@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())) {
return AjaxResult.error("cron表达式不正确");
}
sysJob.setCreateBy(SecurityUtils.getUsername());
return toAjax(jobService.insertJob(sysJob));
}
/**
*
*/
@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())) {
return AjaxResult.error("cron表达式不正确");
}
sysJob.setUpdateBy(SecurityUtils.getUsername());
return toAjax(jobService.updateJob(sysJob));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
SysJob newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/run")
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException {
jobService.run(job);
return AjaxResult.success();
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('monitor:job:remove')")
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobIds}")
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}
}

View File

@ -1,218 +0,0 @@
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;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;
/**
*
*
* @author ruoyi
*/
@Service
public class SysJobServiceImpl implements ISysJobService {
@Autowired
private Scheduler scheduler;
@Autowired
private SysJobMapper jobMapper;
/**
* quartz
*
* @param job
* @return
*/
@Override
public List<SysJob> selectJobList(SysJob job) {
return jobMapper.selectJobList(job);
}
/**
* ID
*
* @param jobId ID
* @return
*/
@Override
public SysJob selectJobById(Long jobId) {
return jobMapper.selectJobById(jobId);
}
/**
*
*
* @param job
*/
@Override
@Transactional
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) {
scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
*
*
* @param job
*/
@Override
@Transactional
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) {
scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
* trigger
*
* @param job
*/
@Override
@Transactional
public int deleteJob(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId);
if (rows > 0) {
scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
}
return rows;
}
/**
*
*
* @param jobIds ID
* @return
*/
@Override
@Transactional
public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
for (Long jobId : jobIds) {
SysJob job = jobMapper.selectJobById(jobId);
deleteJob(job);
}
}
/**
*
*
* @param job
*/
@Override
@Transactional
public int changeStatus(SysJob job) throws SchedulerException {
int rows = 0;
String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
rows = resumeJob(job);
} else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
rows = pauseJob(job);
}
return rows;
}
/**
*
*
* @param job
*/
@Override
@Transactional
public void run(SysJob job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
SysJob properties = selectJobById(job.getJobId());
// 参数
JobDataMap dataMap = new JobDataMap();
dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
}
/**
*
*
* @param job
*/
@Override
@Transactional
public int insertJob(SysJob job) throws SchedulerException, TaskException {
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.insertJob(job);
if (rows > 0) {
ScheduleUtils.createScheduleJob(scheduler, job);
}
return rows;
}
/**
*
*
* @param job
*/
@Override
@Transactional
public int updateJob(SysJob job) throws SchedulerException, TaskException {
SysJob properties = selectJobById(job.getJobId());
int rows = jobMapper.updateJob(job);
if (rows > 0) {
updateSchedulerJob(job, properties.getJobGroup());
}
return rows;
}
/**
*
*
* @param job
* @param jobGroup
*/
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
Long jobId = job.getJobId();
// 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
if (scheduler.checkExists(jobKey)) {
// 防止创建时存在数据问题 先移除,然后在执行创建操作
scheduler.deleteJob(jobKey);
}
ScheduleUtils.createScheduleJob(scheduler, job);
}
/**
* cron
*
* @param cronExpression
* @return
*/
@Override
public boolean checkCronExpressionIsValid(String cronExpression) {
return CronUtils.isValid(cronExpression);
}
}

View File

@ -1,53 +0,0 @@
package com.ruoyi.quartz.util;
import java.text.ParseException;
import java.util.Date;
import org.quartz.CronExpression;
/**
* cron
*
* @author ruoyi
*/
public class CronUtils {
/**
* Cron
*
* @param cronExpression Cron
* @return boolean
*/
public static boolean isValid(String cronExpression) {
return CronExpression.isValidExpression(cronExpression);
}
/**
* ,Cron
*
* @param cronExpression Cron
* @return String ,null
*/
public static String getInvalidMessage(String cronExpression) {
try {
new CronExpression(cronExpression);
return null;
} catch (ParseException pe) {
return pe.getMessage();
}
}
/**
* Cron
*
* @param cronExpression Cron
* @return Date Cron
*/
public static Date getNextExecution(String cronExpression) {
try {
CronExpression cron = new CronExpression(cronExpression);
return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}

View File

@ -46,35 +46,30 @@ export function delJob(jobId) {
// 导出定时任务调度
export function exportJob(query) {
return request({
url: '/infra/job/export',
url: '/infra/job/export-excel',
method: 'get',
params: query
params: query,
responseType: 'blob'
})
}
// 任务状态修改
export function changeJobStatus(jobId, status) {
const data = {
jobId,
status
}
export function updateJobStatus(jobId, status) {
return request({
url: '/monitor/job/changeStatus',
url: '/infra/job/update-status',
method: 'put',
data: data
headers:{
'Content-type': 'application/x-www-form-urlencoded'
},
data: 'id=' + jobId + "&status=" + status,
})
}
// 定时任务立即执行一次
export function runJob(jobId, jobGroup) {
const data = {
jobId,
jobGroup
}
export function runJob(jobId) {
return request({
url: '/monitor/job/run',
method: 'put',
data: data
url: '/infra/job/trigger?id=' + jobId,
method: 'put'
})
}

View File

@ -100,7 +100,7 @@ export const constantRoutes = [
children: [
{
path: 'log',
component: (resolve) => require(['@/views/monitor/job/log'], resolve),
component: (resolve) => require(['@/views/infra/job/log'], resolve),
name: 'JobLog',
meta: { title: '调度日志' }
}

View File

@ -48,3 +48,13 @@ export const ToolCodegenTemplateTypeEnum = {
TREE: 2, // 树形 CRUD
SUB: 3, // 主子表 CRUD
}
/**
* 任务状态的枚举
*/
export const InfJobStatusEnum = {
INIT: 0, // 初始化中
NORMAL: 1, // 开启运行
EXCEPTION: 2, // 异常运行
STOP: 3, // 暂停运行
}

View File

@ -22,11 +22,11 @@
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
v-hasPermi="['monitor:job:add']">新增</el-button>
v-hasPermi="['infra:job:create']">新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
v-hasPermi="['monitor:job:export']">导出</el-button>
v-hasPermi="['infra:job:export']">导出</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="info" icon="el-icon-s-operation" size="mini" @click="handleJobLog"
@ -49,16 +49,17 @@
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
v-hasPermi="['monitor:job:query']">详细</el-button>
<el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row)"
v-hasPermi="['monitor:job:query']">修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-caret-right"
@click="handleRun(scope.row)"
v-hasPermi="['monitor:job:changeStatus']"
>执行一次</el-button>
v-hasPermi="['infra:job:query']">详细</el-button>
<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
v-hasPermi="['infra:job:update']">修改</el-button>
<el-button size="mini" type="text" icon="el-icon-check" @click="handleChangeStatus(scope.row, true)"
v-hasPermi="['infra:job:update']">开启</el-button>
<el-button size="mini" type="text" icon="el-icon-close" @click="handleChangeStatus(scope.row, false)"
v-hasPermi="['infra:job:update']">暂停</el-button>
<el-button size="mini" type="text" icon="el-icon-caret-right" @click="handleRun(scope.row)"
v-hasPermi="['infra:job:trigger']">执行一次</el-button>
<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
v-hasPermi="['infra:job:delete']">删除</el-button>
</template>
</el-table-column>
</el-table>
@ -119,7 +120,8 @@
</template>
<script>
import { listJob, getJob, delJob, addJob, updateJob, exportJob, runJob, changeJobStatus } from "@/api/monitor/job";
import { listJob, getJob, delJob, addJob, updateJob, exportJob, runJob, updateJobStatus } from "@/api/infra/job";
import { InfJobStatusEnum } from "@/utils/constants";
export default {
name: "Job",
@ -199,29 +201,14 @@ export default {
this.resetForm("queryForm");
this.handleQuery();
},
//
handleStatusChange(row) {
let text = row.status === "0" ? "启用" : "停用";
this.$confirm('确认要"' + text + '""' + row.name + '"任务吗?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return changeJobStatus(row.id, row.status);
}).then(() => {
this.msgSuccess(text + "成功");
}).catch(function() {
row.status = row.status === "0" ? "1" : "0";
});
},
/* 立即执行一次 */
/** 立即执行一次 **/
handleRun(row) {
this.$confirm('确认要立即执行一次"' + row.name + '"任务吗?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return runJob(row.id, row.jobGroup);
return runJob(row.id);
}).then(() => {
this.msgSuccess("执行成功");
})
@ -275,7 +262,7 @@ export default {
},
/** 删除按钮操作 */
handleDelete(row) {
const ids = row.id || this.ids;
const ids = row.id;
this.$confirm('是否确认删除定时任务编号为"' + ids + '"的数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
@ -287,6 +274,22 @@ export default {
this.msgSuccess("删除成功");
})
},
/** 更新状态操作 */
handleChangeStatus(row, open) {
const id = row.id;
let status = open ? InfJobStatusEnum.NORMAL : InfJobStatusEnum.STOP;
let statusStr = open ? '开启' : '关闭';
this.$confirm('是否确认' + statusStr + '定时任务编号为"' + id + '"的数据项?', "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(function() {
return updateJobStatus(id, status);
}).then(() => {
this.getList();
this.msgSuccess(statusStr + "成功");
})
},
/** 导出按钮操作 */
handleExport() {
const queryParams = this.queryParams;
@ -297,7 +300,7 @@ export default {
}).then(function() {
return exportJob(queryParams);
}).then(response => {
this.download(response.msg);
this.downloadExcel(response, '定时任务.xls');
})
}
}

File diff suppressed because one or more lines are too long

View File

@ -28,4 +28,8 @@ public interface BaseMapperX<T> extends BaseMapper<T> {
return selectList(new QueryWrapper<>());
}
default T selectOne(String field, Object value) {
return selectOne(new QueryWrapper<T>().eq(field, value));
}
}

View File

@ -7,6 +7,12 @@ import org.quartz.*;
/**
* {@link org.quartz.Scheduler}
*
* 使 jobHandlerName
* 1. Job {@link JobDetail#getKey()}
* 2. Trigger {@link Trigger#getKey()}
*
* jobHandlerName Spring Bean
*
* @author
*/
public class SchedulerManager {
@ -17,6 +23,15 @@ public class SchedulerManager {
this.scheduler = scheduler;
}
/**
* Job Quartz
*
* @param jobId
* @param jobHandlerName
* @param jobHandlerParam
* @param cronExpression CRON
* @throws SchedulerException
*/
public void addJob(Long jobId, String jobHandlerName, String jobHandlerParam, String cronExpression)
throws SchedulerException {
// 创建 JobDetail 对象
@ -30,6 +45,14 @@ public class SchedulerManager {
scheduler.scheduleJob(jobDetail, trigger);
}
/**
* Job Quartz
*
* @param jobHandlerName
* @param jobHandlerParam
* @param cronExpression CRON
* @throws SchedulerException
*/
public void updateJob(String jobHandlerName, String jobHandlerParam, String cronExpression)
throws SchedulerException {
// 创建新 Trigger 对象
@ -38,19 +61,45 @@ public class SchedulerManager {
scheduler.rescheduleJob(new TriggerKey(jobHandlerName), newTrigger);
}
/**
* Quartz Job
*
* @param jobHandlerName
* @throws SchedulerException
*/
public void deleteJob(String jobHandlerName) throws SchedulerException {
scheduler.deleteJob(new JobKey(jobHandlerName));
}
/**
* Quartz Job
*
* @param jobHandlerName
* @throws SchedulerException
*/
public void pauseJob(String jobHandlerName) throws SchedulerException {
scheduler.pauseJob(new JobKey(jobHandlerName));
}
/**
* Quartz Job
*
* @param jobHandlerName
* @throws SchedulerException
*/
public void resumeJob(String jobHandlerName) throws SchedulerException {
scheduler.resumeJob(new JobKey(jobHandlerName));
scheduler.resumeTrigger(new TriggerKey(jobHandlerName));
}
/**
* Quartz Job
*
* @param jobId
* @param jobHandlerName
* @param jobHandlerParam
* @throws SchedulerException
*/
public void triggerJob(Long jobId, String jobHandlerName, String jobHandlerParam)
throws SchedulerException {
JobDataMap data = new JobDataMap();

View File

@ -0,0 +1,22 @@
package cn.iocoder.dashboard.framework.quartz.core.util;
import org.quartz.CronExpression;
/**
* Quartz Cron
*
* @author
*/
public class CronUtils {
/**
* CRON
*
* @param cronExpression CRON
* @return
*/
public static boolean isValid(String cronExpression) {
return CronExpression.isValidExpression(cronExpression);
}
}

View File

@ -10,7 +10,9 @@ import cn.iocoder.dashboard.modules.infra.dal.dataobject.job.InfJobDO;
import cn.iocoder.dashboard.modules.infra.service.job.InfJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -37,30 +39,55 @@ public class InfJobController {
@PostMapping("/create")
@ApiOperation("创建定时任务")
@PreAuthorize("@ss.hasPermission('infra:job:create')")
public CommonResult<Long> createJob(@Valid @RequestBody InfJobCreateReqVO createReqVO) {
public CommonResult<Long> createJob(@Valid @RequestBody InfJobCreateReqVO createReqVO)
throws SchedulerException {
return success(jobService.createJob(createReqVO));
}
@PutMapping("/update")
@ApiOperation("更新定时任务")
@PreAuthorize("@ss.hasPermission('infra:job:update')")
public CommonResult<Boolean> updateJob(@Valid @RequestBody InfJobUpdateReqVO updateReqVO) {
public CommonResult<Boolean> updateJob(@Valid @RequestBody InfJobUpdateReqVO updateReqVO)
throws SchedulerException {
jobService.updateJob(updateReqVO);
return success(true);
}
@PutMapping("/update-status")
@ApiOperation("更新定时任务的状态")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class),
@ApiImplicitParam(name = "status", value = "状态", required = true, example = "1", dataTypeClass = Integer.class),
})
@PreAuthorize("@ss.hasPermission('infra:job:update')")
public CommonResult<Boolean> updateJobStatus(@RequestParam(value = "id") Long id, @RequestParam("status") Integer status)
throws SchedulerException {
jobService.updateJobStatus(id, status);
return success(true);
}
@DeleteMapping("/delete")
@ApiOperation("删除定时任务")
@ApiImplicitParam(name = "id", value = "编号", required = true)
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
@PreAuthorize("@ss.hasPermission('infra:job:delete')")
public CommonResult<Boolean> deleteJob(@RequestParam("id") Long id) {
public CommonResult<Boolean> deleteJob(@RequestParam("id") Long id)
throws SchedulerException {
jobService.deleteJob(id);
return success(true);
}
@PutMapping("/trigger")
@ApiOperation("触发定时任务")
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
@PreAuthorize("@ss.hasPermission('infra:job:trigger')")
public CommonResult<Boolean> triggerJob(@RequestParam("id") Long id) throws SchedulerException {
jobService.triggerJob(id);
return success(true);
}
@GetMapping("/get")
@ApiOperation("获得定时任务")
@ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
@PreAuthorize("@ss.hasPermission('infra:job:query')")
public CommonResult<InfJobRespVO> getJob(@RequestParam("id") Long id) {
InfJobDO job = jobService.getJob(id);

View File

@ -2,13 +2,9 @@ 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.FieldStrategy;
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 lombok.*;
import java.util.Date;
@ -21,6 +17,9 @@ import java.util.Date;
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class InfJobDO extends BaseDO {
/**
@ -45,7 +44,6 @@ public class InfJobDO extends BaseDO {
/**
*
*/
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String handlerParam;
// ========== 时间相关字段 ==========

View File

@ -18,6 +18,10 @@ import java.util.List;
@Mapper
public interface InfJobMapper extends BaseMapperX<InfJobDO> {
default InfJobDO selectByHandlerName(String handlerName) {
return selectOne("handler_name", handlerName);
}
default PageResult<InfJobDO> selectPage(InfJobPageReqVO reqVO) {
return selectPage(reqVO, new QueryWrapperX<InfJobDO>()
.likeIfPresent("name", reqVO.getName())

View File

@ -17,5 +17,10 @@ public interface InfErrorCodeConstants {
// ========== 定时任务 1001001000 ==========
ErrorCode JOB_NOT_EXISTS = new ErrorCode(1001001000, "定时任务不存在");
ErrorCode JOB_HANDLER_EXISTS = new ErrorCode(1001001001, "定时任务的处理器已经存在");
ErrorCode JOB_CHANGE_STATUS_INVALID = new ErrorCode(1001001002, "只允许修改为开启或者关闭状态");
ErrorCode JOB_CHANGE_STATUS_EQUALS = new ErrorCode(1001001003, "定时任务已经处于该状态,无需修改");
ErrorCode JOB_UPDATE_ONLY_NORMAL_STATUS = new ErrorCode(1001001004, "只有开启状态的任务,才可以修改");
ErrorCode JOB_CRON_EXPRESSION_VALID = new ErrorCode(1001001005, "CRON 表达式不正确");
}

View File

@ -6,6 +6,7 @@ import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobExportReqV
import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobPageReqVO;
import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobUpdateReqVO;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.job.InfJobDO;
import org.quartz.SchedulerException;
import javax.validation.Valid;
import java.util.Collection;
@ -24,21 +25,36 @@ public interface InfJobService {
* @param createReqVO
* @return
*/
Long createJob(@Valid InfJobCreateReqVO createReqVO);
Long createJob(@Valid InfJobCreateReqVO createReqVO) throws SchedulerException;
/**
*
*
* @param updateReqVO
*/
void updateJob(@Valid InfJobUpdateReqVO updateReqVO);
void updateJob(@Valid InfJobUpdateReqVO updateReqVO) throws SchedulerException;
/**
*
*
* @param id
* @param status
*/
void updateJobStatus(Long id, Integer status) throws SchedulerException;
/**
*
*
* @param id
*/
void triggerJob(Long id) throws SchedulerException;
/**
*
*
* @param id
*/
void deleteJob(Long id);
void deleteJob(Long id) throws SchedulerException;
/**
*

View File

@ -1,7 +1,8 @@
package cn.iocoder.dashboard.modules.infra.service.job.impl;
import cn.iocoder.dashboard.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.dashboard.common.pojo.PageResult;
import cn.iocoder.dashboard.framework.quartz.core.scheduler.SchedulerManager;
import cn.iocoder.dashboard.framework.quartz.core.util.CronUtils;
import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobCreateReqVO;
import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobExportReqVO;
import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobPageReqVO;
@ -9,15 +10,20 @@ import cn.iocoder.dashboard.modules.infra.controller.job.vo.job.InfJobUpdateReqV
import cn.iocoder.dashboard.modules.infra.convert.job.InfJobConvert;
import cn.iocoder.dashboard.modules.infra.dal.dataobject.job.InfJobDO;
import cn.iocoder.dashboard.modules.infra.dal.mysql.job.InfJobMapper;
import cn.iocoder.dashboard.modules.infra.enums.job.InfJobStatusEnum;
import cn.iocoder.dashboard.modules.infra.service.job.InfJobService;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.JOB_NOT_EXISTS;
import static cn.iocoder.dashboard.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.dashboard.modules.infra.enums.InfErrorCodeConstants.*;
import static cn.iocoder.dashboard.util.collection.CollectionUtils.containsAny;
/**
* Service
@ -31,41 +37,109 @@ public class InfJobServiceImpl implements InfJobService {
@Resource
private InfJobMapper jobMapper;
@Resource
private SchedulerManager schedulerManager;
@Override
public Long createJob(InfJobCreateReqVO createReqVO) {
@Transactional
public Long createJob(InfJobCreateReqVO createReqVO) throws SchedulerException {
validateCronExpression(createReqVO.getCronExpression());
// 校验唯一性
if (jobMapper.selectByHandlerName(createReqVO.getHandlerName()) != null) {
throw exception(JOB_HANDLER_EXISTS);
}
// 插入
InfJobDO job = InfJobConvert.INSTANCE.convert(createReqVO);
if (job.getMonitorTimeout() == null) {
job.setMonitorTimeout(0);
}
job.setStatus(InfJobStatusEnum.INIT.getStatus());
fillJobMonitorTimeoutEmpty(job);
jobMapper.insert(job);
// 添加 Job 到 Quartz 中
schedulerManager.addJob(job.getId(), job.getHandlerName(), job.getHandlerParam(), job.getCronExpression());
// 更新
InfJobDO updateObj = InfJobDO.builder().id(job.getId()).status(InfJobStatusEnum.NORMAL.getStatus()).build();
jobMapper.updateById(updateObj);
// 返回
return job.getId();
}
@Override
public void updateJob(InfJobUpdateReqVO updateReqVO) {
@Transactional
public void updateJob(InfJobUpdateReqVO updateReqVO) throws SchedulerException {
validateCronExpression(updateReqVO.getCronExpression());
// 校验存在
this.validateJobExists(updateReqVO.getId());
InfJobDO job = this.validateJobExists(updateReqVO.getId());
// 只有开启状态,才可以修改.原因是,如果出暂停状态,修改 Quartz Job 时,会导致任务又开始执行
if (!job.getStatus().equals(InfJobStatusEnum.NORMAL.getStatus())) {
throw exception(JOB_UPDATE_ONLY_NORMAL_STATUS);
}
// 更新
InfJobDO updateObj = InfJobConvert.INSTANCE.convert(updateReqVO);
if (updateObj.getMonitorTimeout() == null) {
updateObj.setMonitorTimeout(0);
}
fillJobMonitorTimeoutEmpty(updateObj);
jobMapper.updateById(updateObj);
// 更新 Job 到 Quartz 中
schedulerManager.updateJob(job.getHandlerName(), updateReqVO.getHandlerParam(), updateReqVO.getCronExpression());
}
@Override
public void deleteJob(Long id) {
@Transactional
public void updateJobStatus(Long id, Integer status) throws SchedulerException {
// 校验 status
if (!containsAny(status, InfJobStatusEnum.NORMAL.getStatus(), InfJobStatusEnum.STOP.getStatus())) {
throw exception(JOB_CHANGE_STATUS_INVALID);
}
// 校验存在
this.validateJobExists(id);
// 更新
jobMapper.deleteById(id);
InfJobDO job = this.validateJobExists(id);
// 校验是否已经为当前状态
if (job.getStatus().equals(status)) {
throw exception(JOB_CHANGE_STATUS_EQUALS);
}
// 更新 Job 状态
InfJobDO updateObj = InfJobDO.builder().id(id).status(status).build();
jobMapper.updateById(updateObj);
// 更新状态 Job 到 Quartz 中
if (InfJobStatusEnum.NORMAL.getStatus().equals(status)) { // 开启
schedulerManager.resumeJob(job.getHandlerName());
} else { // 暂停
schedulerManager.pauseJob(job.getHandlerName());
}
}
private void validateJobExists(Long id) {
if (jobMapper.selectById(id) == null) {
throw ServiceExceptionUtil.exception(JOB_NOT_EXISTS);
@Override
public void triggerJob(Long id) throws SchedulerException {
// 校验存在
InfJobDO job = this.validateJobExists(id);
// 触发 Quartz 中的 Job
schedulerManager.triggerJob(job.getId(), job.getHandlerName(), job.getHandlerParam());
}
@Override
@Transactional
public void deleteJob(Long id) throws SchedulerException {
// 校验存在
InfJobDO job = this.validateJobExists(id);
// 更新
jobMapper.deleteById(id);
// 删除 Job 到 Quartz 中
schedulerManager.deleteJob(job.getHandlerName());
}
private InfJobDO validateJobExists(Long id) {
InfJobDO job = jobMapper.selectById(id);
if (job == null) {
throw exception(JOB_NOT_EXISTS);
}
return job;
}
private void validateCronExpression(String cronExpression) {
if (CronUtils.isValid(cronExpression)) {
throw exception(JOB_CRON_EXPRESSION_VALID);
}
}
@ -89,4 +163,10 @@ public class InfJobServiceImpl implements InfJobService {
return jobMapper.selectList(exportReqVO);
}
private static void fillJobMonitorTimeoutEmpty(InfJobDO job) {
if (job.getMonitorTimeout() == null) {
job.setMonitorTimeout(0);
}
}
}

View File

@ -15,6 +15,10 @@ import java.util.stream.Collectors;
*/
public class CollectionUtils {
public static boolean containsAny(Object source, Object... targets) {
return Arrays.asList(targets).contains(source);
}
public static boolean isAnyEmpty(Collection<?>... collections) {
return Arrays.stream(collections).anyMatch(CollectionUtil::isEmpty);
}

View File

@ -63,7 +63,7 @@ public class ${table.className}Controller {
@GetMapping("/get")
@ApiOperation("获得${table.classComment}")
@ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = ${primaryColumn.javaType}.class)
@ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = ${primaryColumn.javaType}.class)
@PreAuthorize("@ss.hasPermission('${permissionPrefix}:query')")
public CommonResult<${table.className}RespVO> get${simpleClassName}(@RequestParam("id") ${primaryColumn.javaType} id) {
${table.className}DO ${classNameVar} = ${classNameVar}Service.get${simpleClassName}(id);
@ -72,7 +72,7 @@ public class ${table.className}Controller {
@GetMapping("/list")
@ApiOperation("获得${table.classComment}列表")
@ApiImplicitParam(name = "ids", value = "编号列表", required = true, dataTypeClass = List.class)
@ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
@PreAuthorize("@ss.hasPermission('${permissionPrefix}:query')")
public CommonResult<List<${table.className}RespVO>> get${simpleClassName}List(@RequestParam("ids") Collection<${primaryColumn.javaType}> ids) {
List<${table.className}DO> list = ${classNameVar}Service.get${simpleClassName}List(ids);