springboot定时器动态mysql_springboot动态配置定时器

本文介绍了如何在SpringBoot中使用MySQL存储定时任务信息,包括创建定时任务数据表、编写实体类、服务接口及其实现,以及使用Quartz进行定时任务的创建、更新、暂停、恢复和删除操作。此外,还提供了定时任务控制器用于API交互。
摘要由CSDN通过智能技术生成

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

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 implements IScheduleJobService {

@Autowired

private Scheduler scheduler;

/**

* 项目启动时,初始化定时器

*/

@PostConstruct

public void init(){

List scheduleJobList = this.baseMapper.selectList(Wrappers.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 {

}

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 {

}

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 implements IScheduleJobLogService {

}

接下来就是定时器的工具类先在pom引入所需的jar包

org.springframework.boot

spring-boot-starter-quartz

自定义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 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 Result success() {

return build(ResultCode.SUCCESS);

}

public static Result success(T data) {

return build(ResultCode.SUCCESS, data);

}

public static Result success(String msg) {

return build(ResultCode.SUCCESS, msg);

}

public static Result success(T data, String msg) {

return build(ResultCode.SUCCESS, data, msg);

}

public static Result build(IResultCode resultCode) {

return build(resultCode, null, resultCode.getMsg());

}

public static Result build(IResultCode resultCode, T data) {

return build(resultCode, data, resultCode.getMsg());

}

public static Result build(IResultCode resultCode, String msg) {

return build(resultCode, null, msg);

}

public static Result build(IResultCode resultCode, T data, String msg) {

return new Result<>(resultCode, data, msg);

}

public static Result 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 Result fail(T data) {

return build(ResultCode.FAILURE, data);

}

public static Result 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 getBean(String name, Class 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.*;

/**

*

* 定时器 前端控制器

*

* @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就可以看到我们刚才写的

957cdb16feb0942037df4c00c7557f0b.png

接下来我们一个个测试,先测试添加定时器

33549dda93573f5753543413c681971e.png

6553bca935bb16f4e010d1601a0c5122.png

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

84c502ea26959f3ea083d11b5bace031.png

数据库对应保存的记录

cda5ebae82382c6dd35e6408036f9f38.png

接下来我们测试修改

23d57672519d2e8a5f34b81263e97e6c.png

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

efd434a893a228a17c53af894c2a231e.png

数据库也是

2ed0411067556a44fc26a9647628ecfc.png

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

以下是Spring Boot动态定时器配置文件的示例: 1. 创建一个配置文件,例如dynamic-tasks.properties。 2. 在文件中添加以下内容: ``` # 配置动态任务 tasks[0].name=Task1 tasks[0].cron=0 * * * * ? tasks[0].enabled=true tasks[1].name=Task2 tasks[1].cron=0 0 * * * ? tasks[1].enabled=false ``` 3. 创建一个DynamicTask类,用于读取和解析配置文件: ```java @Configuration @ConfigurationProperties(prefix = "tasks") public class DynamicTask { private List<Task> list = new ArrayList<>(); public List<Task> getList() { return list; } public void setList(List<Task> list) { this.list = list; } public static class Task { private String name; private String cron; private boolean enabled; // getters and setters } } ``` 4. 创建一个ScheduledTaskRegistrar类,用于注册定时器任务: ```java @Configuration @EnableScheduling public class ScheduledTaskRegistrar { @Autowired private DynamicTask dynamicTask; @Autowired private TaskScheduler taskScheduler; @PostConstruct public void init() { for (DynamicTask.Task task : dynamicTask.getList()) { if (task.isEnabled()) { taskScheduler.schedule(new Runnable() { @Override public void run() { // 定时器任务逻辑 } }, new CronTrigger(task.getCron())); } } } } ``` 5. 在启动类中添加@EnableConfigurationProperties注解,以启用配置文件属性: ```java @SpringBootApplication @EnableConfigurationProperties(DynamicTask.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 6. 运行应用程序,动态定时器将从配置文件中加载任务并启动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值