首先创建有关定时任务的数据表,我这边用的是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秒打印一次

数据库也是

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




 
 
 
 




 
 
 
 
 



02-14 00:47