首先創建有關定時任務的數據表,我這邊用的是mysql,下面是創建語句
CREATE TABLE `schedule_job` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任務id',
`name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'spring bean名稱',
`method_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '方法名',
`cron` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'cron表達式',
`status` int(1) NULL DEFAULT NULL COMMENT '任務狀態 0:正常 1:暫停 -1:刪除',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '創建時間',
`params` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '參數',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '定時任務' ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
CREATE TABLE `schedule_job_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '任務日志id',
`job_id` bigint(20) NOT NULL COMMENT '任務id',
`name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'spring bean名稱',
`method_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '方法名',
`status` tinyint(4) NOT NULL COMMENT '任務狀態 0:成功 1:失敗',
`error` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '失敗信息',
`times` int(11) NOT NULL COMMENT '耗時(單位:毫秒)',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '創建時間',
`params` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 82 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '定時任務日志' ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
表創建好了,接下來寫對應的實體,service,mapper
ScheduleJob
package com.eshore.mlxc.entity;
import com.eshore.khala.core.annotation.IdType;
import com.eshore.khala.core.annotation.TableId;
import com.eshore.khala.core.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* 定時器
* @author chengp
* @Date 2020-02-11
*/
@SuppressWarnings("serial")
@Data
@TableName(value = "schedule_job")
@NoArgsConstructor
@AllArgsConstructor
public class ScheduleJob implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
private String name; //spring bean名稱
private String methodName;
private String params;
private String cron;
private Integer status;
private Date createTime;
}
ScheduleJobLog
package com.eshore.mlxc.entity;
import com.eshore.khala.core.annotation.IdType;
import com.eshore.khala.core.annotation.TableId;
import com.eshore.khala.core.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* 定時器日志
* @author chengp
* @Date 2020-02-11
*/
@SuppressWarnings("serial")
@Data
@TableName(value = "schedule_job_log")
@NoArgsConstructor
@AllArgsConstructor
public class ScheduleJobLog implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
private Integer jobId;
private String name; //spring bean名稱
private String methodName;
private String params;
private Integer status;
private String error;
private Integer times;
private Date createTime;
}
ScheduleJobRequest 保存修改時的參數
package com.eshore.mlxc.wx.web.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ScheduleJobRequest implements Serializable {
@ApiModelProperty(value = "id(修改時為必須)")
private Integer id;
@ApiModelProperty(value = "spring bean名稱(大喇叭定時器默認horn)", required = true)
private String name;
@ApiModelProperty(value = "方法名(大喇叭定時器默認horn)", required = true)
private String methodName;
@ApiModelProperty(value = "參數(備注)", required = true)
private String params;
@ApiModelProperty(value = "定時器執行計划(0/10 * * * * ? 每隔10秒一次)", required = true)
private String cron;
}
等下會用到的常量
package com.eshore.mlxc.constant;
public class Constant {
/**
* 任務調度參數key
*/
public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";
/**
* 定時任務狀態
*
*/
/**
* 正常
*/
public static final int NORMAL = 0;
/**
* 暫停
*/
public static final int PAUSE =1;
/**
* 刪除
*/
public static final int DEL =-1;
public static final int SUCCESS =0;
public static final int FAIL =1;
}
ScheduleJobService
package com.eshore.mlxc.service;
import com.eshore.khala.core.extension.service.IService;
import com.eshore.mlxc.entity.ScheduleJob;
import com.eshore.mlxc.wx.web.vo.ScheduleJobRequest;
/**
* Created by chengp on 2020/2/11.
*/
public interface IScheduleJobService extends IService<ScheduleJob> {
void saveScheduleJob (ScheduleJobRequest req);
void updateScheduleJob(ScheduleJobRequest req);
void run(Integer id);
void del(Integer id);
/**
* 暫停定時器
* @param id
*/
void pause(Integer id);
/**
* 恢復定時器
* @param id
*/
void resume(Integer id);
}
ScheduleJobServiceImpl
package com.eshore.mlxc.service.impl;
import com.eshore.khala.core.extension.service.impl.ServiceImpl;
import com.eshore.khala.core.kernel.toolkit.Wrappers;
import com.eshore.mlxc.constant.Constant;
import com.eshore.mlxc.entity.ScheduleJob;
import com.eshore.mlxc.mapper.ScheduleJobMapper;
import com.eshore.mlxc.service.IScheduleJobService;
import com.eshore.mlxc.wx.schedule.ScheduleUtils;
import com.eshore.mlxc.wx.web.vo.ScheduleJobRequest;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
/**
* Created by chengp on 2020/2/11.
*/
@Service
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobMapper, ScheduleJob> implements IScheduleJobService {
@Autowired
private Scheduler scheduler;
/**
* 項目啟動時,初始化定時器
*/
@PostConstruct
public void init(){
List<ScheduleJob> scheduleJobList = this.baseMapper.selectList(Wrappers.<ScheduleJob>lambdaQuery().ne(ScheduleJob::getStatus,Constant.DEL));
for(ScheduleJob scheduleJob : scheduleJobList){
CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
//如果不存在,則創建
if(cronTrigger == null) {
ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
}else {
ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void saveScheduleJob(ScheduleJobRequest req) {
ScheduleJob entity = buildEntity(req);
this.baseMapper.insert(entity);
ScheduleUtils.createScheduleJob(scheduler, entity);
}
@Override
public void updateScheduleJob(ScheduleJobRequest req) {
ScheduleJob entity = buildEntity(req);
ScheduleUtils.updateScheduleJob(scheduler, entity);
this.baseMapper.updateById(entity);
}
@Override
public void run(Integer id) {
ScheduleUtils.run(scheduler,this.baseMapper.selectById(id));
}
@Override
public void del(Integer id) {
ScheduleUtils.deleteScheduleJob(scheduler, id);
ScheduleJob scheduleJob = this.baseMapper.selectById(id);
scheduleJob.setStatus(Constant.DEL);
this.baseMapper.updateById(scheduleJob);
}
@Override
public void pause(Integer id) {
ScheduleUtils.pauseJob(scheduler, id);
ScheduleJob scheduleJob = this.baseMapper.selectById(id);
scheduleJob.setStatus(Constant.PAUSE);
this.baseMapper.updateById(scheduleJob);
}
@Override
public void resume(Integer id) {
ScheduleUtils.resumeJob(scheduler, id);
ScheduleJob scheduleJob = this.baseMapper.selectById(id);
scheduleJob.setStatus(Constant.NORMAL);
this.baseMapper.updateById(scheduleJob);
}
private ScheduleJob buildEntity(ScheduleJobRequest req){
ScheduleJob entity = new ScheduleJob();
if(req.getId() != null){
entity.setId(req.getId());
}else{
entity.setCreateTime(new Date());
}
entity.setStatus(Constant.NORMAL);
entity.setCron(req.getCron());
entity.setMethodName(req.getMethodName());
entity.setName(req.getName());
entity.setParams(req.getParams());
return entity;
}
}
ScheduleJobMapper
package com.eshore.mlxc.mapper;
import com.eshore.khala.core.kernel.mapper.BaseMapper;
import com.eshore.mlxc.entity.ScheduleJob;
/**
* Created by chengp on 2020/2/11.
*/
public interface ScheduleJobMapper extends BaseMapper<ScheduleJob> {
}
ScheduleJobLogService
package com.eshore.mlxc.service;
import com.eshore.khala.core.extension.service.IService;
import com.eshore.mlxc.entity.ScheduleJobLog;
/**
* Created by chengp on 2020/2/11.
*/
public interface IScheduleJobLogService extends IService<ScheduleJobLog> {
}
ScheduleJobLogServiceImpl
package com.eshore.mlxc.service.impl;
import com.eshore.khala.core.extension.service.impl.ServiceImpl;
import com.eshore.mlxc.entity.ScheduleJobLog;
import com.eshore.mlxc.mapper.ScheduleJobLogMapper;
import com.eshore.mlxc.service.IScheduleJobLogService;
import org.springframework.stereotype.Service;
/**
* Created by chengp on 2020/2/11.
*/
@Service
public class ScheduleJobLogServiceImpl extends ServiceImpl<ScheduleJobLogMapper, ScheduleJobLog> implements IScheduleJobLogService {
}
接下來就是定時器的工具類先在pom引入所需的jar包
<!--定時器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
自定義exception工具類
package com.eshore.mlxc.admin.exception;
import lombok.*;
import java.io.Serializable;
/**
* 接口請求異常類
*
* @author chengp
*/
@Getter
public class ApiException extends RuntimeException {
/**
* 錯誤碼
*/
private int code;
public ApiException(IResultCode resultCode) {
this(resultCode.getCode(), resultCode.getMsg());
}
public ApiException(String msg) {
this(ResultCode.FAILURE.getCode(), msg);
}
public ApiException(int code, String msg) {
super(msg);
this.code = code;
}
public ApiException(Throwable cause) {
super(cause);
this.code = ResultCode.FAILURE.getCode();
}
}
ResultCode
package com.eshore.mlxc.admin.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 業務狀態碼枚舉
*
* @author chengp
*/
@Getter
@AllArgsConstructor
public enum ResultCode implements IResultCode {
/**
* 操作成功
*/
SUCCESS(0, "執行成功"),
/**
* 業務異常
*/
FAILURE(-1, "操作失敗");
/**
* 狀態碼
*/
private final int code;
/**
* 消息
*/
private final String msg;
}
Result
package com.eshore.mlxc.admin.support;
import com.eshore.mlxc.admin.exception.ApiException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* @author chegnp
*/
@Data
@ToString
@ApiModel(description = "返回消息")
public class Result<T> implements Serializable {
@ApiModelProperty(value = "狀態碼", required = true)
private int code;
@ApiModelProperty(value = "是否成功", required = true)
private boolean success;
@ApiModelProperty(value = "返回消息", required = true)
private String msg;
@ApiModelProperty("承載數據")
private T data;
private Result(IResultCode resultCode, T data, String msg) {
this(resultCode.getCode(), data, msg);
}
private Result(int code, T data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
this.success = ResultCode.SUCCESS.getCode() == code;
}
public static <T> Result<T> success() {
return build(ResultCode.SUCCESS);
}
public static <T> Result<T> success(T data) {
return build(ResultCode.SUCCESS, data);
}
public static <T> Result<T> success(String msg) {
return build(ResultCode.SUCCESS, msg);
}
public static <T> Result<T> success(T data, String msg) {
return build(ResultCode.SUCCESS, data, msg);
}
public static <T> Result<T> build(IResultCode resultCode) {
return build(resultCode, null, resultCode.getMsg());
}
public static <T> Result<T> build(IResultCode resultCode, T data) {
return build(resultCode, data, resultCode.getMsg());
}
public static <T> Result<T> build(IResultCode resultCode, String msg) {
return build(resultCode, null, msg);
}
public static <T> Result<T> build(IResultCode resultCode, T data, String msg) {
return new Result<>(resultCode, data, msg);
}
public static <T> Result<T> build(int code, String msg) {
return new Result<>(code, null, msg);
}
public static Result fail(String msg) {
return build(ResultCode.FAILURE, msg);
}
public static Result fail(IResultCode resultCode) {
return build(resultCode);
}
public static Result fail(ApiException e) {
return new Result(e.getCode(), null, e.getMessage());
}
public static <T> Result<T> fail(T data) {
return build(ResultCode.FAILURE, data);
}
public static <T> Result<T> fail(T data, String msg) {
return build(ResultCode.FAILURE, data, msg);
}
}
IResultCode
package com.eshore.mlxc.admin.support;
/**
* 業務狀態碼接口
*
* @author chengp
*/
public interface IResultCode {
/**
* 狀態碼
*
* @return int
*/
int getCode();
/**
* 消息
*
* @return String
*/
String getMsg();
}
全局異常處理GlobalExceptionHandler
package com.eshore.mlxc.admin.handler;
import com.eshore.mlxc.admin.exception.ApiException;
import com.eshore.mlxc.admin.support.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局統一異常處理
*
* @author chengp
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Api接口自定義異常攔截
*
* @param e Api接口自定義異常
* @return 錯誤返回消息
*/
@ExceptionHandler(ApiException.class)
public Result apiExceptionHandler(ApiException e) {
log.info("Api接口自定義異常:{}", e.getMessage());
return Result.fail(e);
}
}
ScheduleJobUtils
package com.eshore.mlxc.wx.schedule;
import com.eshore.mlxc.constant.Constant;
import com.eshore.mlxc.entity.ScheduleJob;
import com.eshore.mlxc.entity.ScheduleJobLog;
import com.eshore.mlxc.service.IScheduleJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Slf4j
@Component
public class ScheduleJobUtils extends QuartzJobBean {
private ExecutorService service = Executors.newSingleThreadExecutor();
@Autowired
private IScheduleJobLogService scheduleJobLogService;
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap()
.get(Constant.JOB_PARAM_KEY);
//數據庫保存執行記錄
ScheduleJobLog jobLog = new ScheduleJobLog();
jobLog.setJobId(scheduleJob.getId());
jobLog.setName(scheduleJob.getName());
jobLog.setMethodName(scheduleJob.getMethodName());
jobLog.setParams(scheduleJob.getParams());
jobLog.setCreateTime(new Date());
//任務開始時間
long startTime = System.currentTimeMillis();
Byte zero = 0;
Byte one=1;
try {
//執行任務
log.info("任務准備執行,任務ID:" + scheduleJob.getId());
ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getName(),
scheduleJob.getMethodName(), scheduleJob.getParams());
Future<?> future = service.submit(task);
future.get();
//任務執行總時長
long times = System.currentTimeMillis() - startTime;
jobLog.setTimes((int)times);
//任務狀態 0:成功 1:失敗
jobLog.setStatus(Constant.SUCCESS);
log.info("任務執行完畢,任務ID:" + scheduleJob.getId() + " 總共耗時:" + times + "毫秒");
} catch (Exception e) {
log.error("任務執行失敗,任務ID:" + scheduleJob.getId(), e);
//任務執行總時長
long times = System.currentTimeMillis() - startTime;
jobLog.setTimes((int)times);
//任務狀態 0:成功 1:失敗
jobLog.setStatus(Constant.FAIL);
jobLog.setError(StringUtils.substring(e.toString(), 0, 2000));
}finally {
scheduleJobLogService.save(jobLog);
}
}
}
SpringContextUtils
package com.eshore.mlxc.wx.schedule;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring Context 工具類
* chengp
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}
ScheduleUtils
package com.eshore.mlxc.wx.schedule;
import com.eshore.mlxc.admin.exception.ApiException;
import com.eshore.mlxc.constant.Constant;
import com.eshore.mlxc.entity.ScheduleJob;
import org.quartz.*;
/**
* 定時任務工具類
* chengp
*/
public class ScheduleUtils {
private final static String JOB_NAME = "TASK_";
/**
* 獲取觸發器key
*/
public static TriggerKey getTriggerKey(Integer jobId) {
return TriggerKey.triggerKey(JOB_NAME + jobId);
}
/**
* 獲取jobKey
*/
public static JobKey getJobKey(Integer jobId) {
return JobKey.jobKey(JOB_NAME + jobId);
}
/**
* 獲取表達式觸發器
*/
public static CronTrigger getCronTrigger(Scheduler scheduler, Integer jobId) {
try {
return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
} catch (SchedulerException e) {
throw new ApiException(-1,"獲取定時任務CronTrigger出現異常");
}
}
/**
* 創建定時任務
*/
public static void createScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {
try {
//構建job信息
JobDetail jobDetail = JobBuilder.newJob(ScheduleJobUtils.class).withIdentity(getJobKey(scheduleJob.getId())).build();
//表達式調度構建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron())
.withMisfireHandlingInstructionDoNothing();
//按新的cronExpression表達式構建一個新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(scheduleBuilder).build();
//放入參數,運行時的方法可以獲取
jobDetail.getJobDataMap().put(Constant.JOB_PARAM_KEY, scheduleJob);
scheduler.scheduleJob(jobDetail, trigger);
//暫停任務
if(scheduleJob.getStatus() == Constant.PAUSE){
pauseJob(scheduler, scheduleJob.getId());
}
} catch (SchedulerException e) {
throw new ApiException(-1,"創建定時任務失敗");
}
}
/**
* 更新定時任務
*/
public static void updateScheduleJob(Scheduler scheduler, ScheduleJob scheduleJob) {
try {
TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());
//表達式調度構建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron())
.withMisfireHandlingInstructionDoNothing();
CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
//按新的cronExpression表達式重新構建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//參數
trigger.getJobDataMap().put(Constant.JOB_PARAM_KEY, scheduleJob);
scheduler.rescheduleJob(triggerKey, trigger);
//暫停任務
if(scheduleJob.getStatus() == Constant.PAUSE){
pauseJob(scheduler, scheduleJob.getId());
}
} catch (SchedulerException e) {
throw new ApiException(-1,"更新定時任務失敗");
}
}
/**
* 立即執行任務
*/
public static void run(Scheduler scheduler, ScheduleJob scheduleJob) {
try {
//參數
JobDataMap dataMap = new JobDataMap();
dataMap.put(Constant.JOB_PARAM_KEY, scheduleJob);
scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
} catch (SchedulerException e) {
throw new ApiException(-1,"立即執行定時任務失敗");
}
}
/**
* 暫停任務
*/
public static void pauseJob(Scheduler scheduler, Integer jobId) {
try {
scheduler.pauseJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new ApiException(-1,"暫停定時任務失敗");
}
}
/**
* 恢復任務
*/
public static void resumeJob(Scheduler scheduler, Integer jobId) {
try {
scheduler.resumeJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new ApiException(-1,"暫停定時任務失敗");
}
}
/**
* 刪除定時任務
*/
public static void deleteScheduleJob(Scheduler scheduler, Integer jobId) {
try {
scheduler.deleteJob(getJobKey(jobId));
} catch (SchedulerException e) {
throw new ApiException(-1,"刪除定時任務失敗");
}
}
}
ScheduleRunnable
package com.eshore.mlxc.wx.schedule;
import com.eshore.mlxc.admin.exception.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
/**
* 執行定時任務實現
* chengp
*/
public class ScheduleRunnable implements Runnable{
private Object target;
private Method method;
private String params;
public ScheduleRunnable(String beanName, String methodName, String params) throws NoSuchMethodException, SecurityException {
this.target = SpringContextUtils.getBean(beanName);
this.params = params;
if(StringUtils.isNotBlank(params)){
this.method = target.getClass().getDeclaredMethod(methodName, String.class);
}else{
this.method = target.getClass().getDeclaredMethod(methodName);
}
}
@Override
public void run() {
try {
ReflectionUtils.makeAccessible(method);
if(StringUtils.isNotBlank(params)){
method.invoke(target, params);
}else{
method.invoke(target);
}
}catch (java.lang.Exception e) {
throw new ApiException(-1,"執行定時任務失敗");
}
}
}
數據庫需要的bean_name 以及方法名
package com.eshore.mlxc.wx.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 大喇叭定時器
*/
@Component("horn")
@Slf4j
public class horn {
public void horn(String params){
log.info("我是帶參數的horn方法,正在被執行,參數為:" + params);
}
}
最后編寫定時器的controller
package com.eshore.mlxc.wx.web.Controller;
import com.eshore.khala.core.starter.web.controller.BaseController;
import com.eshore.mlxc.admin.support.Result;
import com.eshore.mlxc.admin.web.vo.FarmProjectPage;
import com.eshore.mlxc.entity.ScheduleJob;
import com.eshore.mlxc.service.IScheduleJobService;
import com.eshore.mlxc.service.farm.IFarmService;
import com.eshore.mlxc.wx.web.vo.ScheduleJobRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 定時器 前端控制器
* </p>
* @author chengp
* @Date 2020-02-14
*/
@RestController
@Api(tags = "定時器")
@RequestMapping("/api/schedulejob")
public class ScheduleJobController extends BaseController {
@Autowired
private IScheduleJobService scheduleJobService;
@PostMapping(value = "/save")
@ApiOperation(value = "保存", notes = "保存")
public Result save(ScheduleJobRequest job) {
scheduleJobService.saveScheduleJob(job);
return Result.success();
}
@PostMapping(value = "/update")
@ApiOperation(value = "修改", notes = "修改")
public Result update(ScheduleJobRequest job) {
scheduleJobService.updateScheduleJob(job);
return Result.success();
}
@GetMapping(value = "/run")
@ApiOperation(value = "執行任務", notes = "執行任務")
public Result run(@RequestParam(required = true) @ApiParam(value="id",required = true) Integer id) {
scheduleJobService.run(id);
return Result.success();
}
@GetMapping(value = "/del")
@ApiOperation(value = "刪除任務", notes = "刪除任務")
public Result del(@RequestParam(required = true) @ApiParam(value="id",required = true)Integer id) {
scheduleJobService.del(id);
return Result.success();
}
@GetMapping(value = "/pause")
@ApiOperation(value = "暫停任務", notes = "暫停任務")
public Result pause(@RequestParam(required = true) @ApiParam(value="id",required = true)Integer id) {
scheduleJobService.pause(id);
return Result.success();
}
@GetMapping(value = "/resume")
@ApiOperation(value = "恢復任務", notes = "恢復任務")
public Result resume(@RequestParam(required = true) @ApiParam(value="id",required = true)Integer id) {
scheduleJobService.resume(id);
return Result.success();
}
}
啟動項目,打開swagger就可以看到我們剛才寫的

接下來我們一個個測試,先測試添加定時器


添加成功,然后可以看到控制台的打印記錄

數據庫對應保存的記錄

接下來我們測試修改

可以看到控制台每20秒打印一次

數據庫也是

其它的方法我就不展示了。
