其他分享
首页 > 其他分享> > 实现一个任务调度引擎系统

实现一个任务调度引擎系统

作者:互联网

目录

该系统主要用于业务系统的定时任务抽离且统一管理

一,引入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

二,创建表

/*
 Navicat Premium Data Transfer

 Source Server         : 【大有中城】E2E电商系统
 Source Server Type    : MySQL
 Source Server Version : 50640
 Source Host           : 172.16.2.221:3306
 Source Schema         : cronjob_engine

 Target Server Type    : MySQL
 Target Server Version : 50640
 File Encoding         : 65001

 Date: 14/01/2022 10:46:02
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for cron_info
-- ----------------------------
DROP TABLE IF EXISTS `cron_info`;
CREATE TABLE `cron_info`  (
  `cron_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '主键',
  `service_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '服务器id',
  `cron_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '定时任务名称',
  `cron_expression` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '正则表达式',
  `cron_uri` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '定时任务执行的逻辑接口uri',
  `cron_status` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '1:已开启    2:已停止',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
  `status` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '1:正常    0:删除',
  `memo` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`cron_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of cron_info
-- ----------------------------
INSERT INTO `cron_info` VALUES ('1234623423436324', 'g51h234io5g123', '测试任务2555', '0/2 * * * * ?', '/user/list2', '2', '2022-01-12 16:28:45', '2022-01-14 09:30:40', '1', '测试定时任务,每五秒运行一次');
INSERT INTO `cron_info` VALUES ('123462346324', 'g51h234io5g123234', '测试任务3333', '0/6 * * * * ?', '/user/list', '2', '2022-01-12 16:28:45', '2022-01-13 18:25:15', '1', '测试定时任务,每五秒运行一次');

-- ----------------------------
-- Table structure for service_info
-- ----------------------------
DROP TABLE IF EXISTS `service_info`;
CREATE TABLE `service_info`  (
  `service_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '主键',
  `service_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '服务器名称',
  `service_ip` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '服务器ip地址',
  `service_port` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '服务端口号',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
  `status` varchar(5) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '1:正常    0:删除',
  PRIMARY KEY (`service_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of service_info
-- ----------------------------
INSERT INTO `service_info` VALUES ('faefe07997994e828eb6492ba525de45', '1231222222', '12312', '12', '2022-01-13 15:31:50', '2022-01-13 15:39:07', '0');
INSERT INTO `service_info` VALUES ('g51h234io5g123', '221服务器', 'http://172.16.2.221', '80', '2022-01-13 12:02:05', '2022-01-13 12:02:07', '1');
INSERT INTO `service_info` VALUES ('g51h234io5g123234', '115服务器', 'http://172.16.2.115', '80', '2022-01-13 12:02:05', '2022-01-13 12:02:07', '1');

SET FOREIGN_KEY_CHECKS = 1;

三,yml配置

都是简单的普通配置

spring:
  datasource:
    url: jdbc:mysql://123.124.209.84:3306/cronjob_engine?useUnicode=true&characterEncoding=utf-8
    username: poc1
    password: poc1@321
    driver-class-name: com.mysql.cj.jdbc.Driver
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
logging:
  level:
    com.example.demo.dao : debug

四,com.dayouzc.cronjob.config

public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(CronjobApplication.class);
    }
}
/**
 * @author FanJiangFeng
 * @createTime 2022年01月13日 14:42:00
 *
 * 动态操作定时任务的全靠SchedulingConfigurer类
 * 关于SchedulingConfigurer类的讲解(推荐):https://cloud.tencent.com/developer/article/1362794
 */
@Configuration
@EnableScheduling
public class DynamicTask implements SchedulingConfigurer{
    @Autowired
    private CronInfoService cronInfoService;
    @Autowired
    private ServiceInfoService serviceInfoService;

    //定时任务注册器
    private volatile ScheduledTaskRegistrar registrar;

    //ScheduledFuture 真正的定时任务执行者
    //这里key = taskId(任务id,自定义,唯一标识) value = 定时任务实例
    private final ConcurrentHashMap<String, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();

    //CronTask 真正的定时任务
    //这里key = taskId(任务id,自定义,唯一标识) value = 定时任务
    private final ConcurrentHashMap<String, CronTask> cronTasks = new ConcurrentHashMap<>();

    //任务对象信息集合
    private volatile List<TaskConstant> taskConstants = new ArrayList<>();

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        this.registrar = registrar;
        /**
         * 给定时任务注册器中添加一个Trigger(PeriodicTrigger),五秒已执行,根据目前的taskConstants自定义任务对象集合更新系统的定时任务
         * Trigger接口
         *      CronTrigger实现类
         *      PeriodicTrigger实现类
         * 具体CronTrigger和PeriodicTrigger的区别见文章:https://blog.csdn.net/qq_39720208/article/details/120970665
         */
        this.registrar.addTriggerTask(() -> {
                    //定时轮询自定义任务对象,如果自定义任务对象集合不为空,并把自定义任务对象信息装载到TimingTask中
                    if (!CollectionUtils.isEmpty(taskConstants)) {
                        System.out.println("检测动态定时任务列表...");
                        List<TimingTask> tts = new ArrayList<>();
                        taskConstants
                                .forEach(taskConstant -> {
                                    TimingTask tt = new TimingTask();
                                    tt.setExpression(taskConstant.getCron());
                                    tt.setTaskId(taskConstant.getTaskId());
                                    tts.add(tt);
                                });
                        //刷新任务状态
                        this.refreshTasks(tts);
                    }
                }
                , triggerContext -> new PeriodicTrigger(5L, TimeUnit.SECONDS).nextExecutionTime(triggerContext));
    }


    public List<TaskConstant> getTaskConstants() {
        return taskConstants;
    }

    /**
     * 根据taskId停止任务
     * @param taskId 任务id
     */
    public void stopTaskByTaskId(String taskId){
        ScheduledFuture<?> scheduledFuture = scheduledFutures.get(taskId);
        if(scheduledFuture != null){
            System.out.println("------------------- 删除任务成功!! ----------------");
            scheduledFuture.cancel(true);
        }else{
            System.out.println("------------------- 删除任务失败!! ----------------");
        }
    }

    /**
     * 根据taskId和cron开启一个新任务
     * @param taskId 任务id
     * @param cron 正则表达式
     */
    public void startTask(String taskId,String cron){
        List<DynamicTask.TaskConstant> taskConstants = getTaskConstants();
        ScheduledFuture<?> scheduledFuture = scheduledFutures.remove(taskId);
        if(scheduledFuture != null){
            scheduledFuture.cancel(true);
        }
        //添加新任务
        DynamicTask.TaskConstant taskConstant = new DynamicTask.TaskConstant();
        taskConstant.setCron(cron);
        taskConstant.setTaskId(taskId);
        taskConstants.add(taskConstant);
        System.out.println("------------------- 添加新任务成功!! ----------------");
    }


    /**
     * 刷新任务状态
     * @param tasks List<TimingTask>
     */
    private void refreshTasks(List<TimingTask> tasks) {
        //遍历taskId列表,如果taskId对应的任务已经不存在了,则取消系统中该任务的执行
        Set<String> taskIds = scheduledFutures.keySet();
        for (String taskId : taskIds) {
            if (!exists(tasks, taskId)) {
                scheduledFutures.get(taskId).cancel(false);
            }
        }
        //对所有定时任务信息进行遍历
        for (TimingTask tt : tasks) {
            //校验正则表达式是否合法
            String expression = tt.getExpression();
            if (StringUtils.isBlank(expression) || !CronSequenceGenerator.isValidExpression(expression)) {
                System.out.println("定时任务DynamicTask cron表达式不合法: " + expression);
                continue;
            }
            //如果配置一致,则不需要重新创建定时任务
            if (scheduledFutures.containsKey(tt.getTaskId())
                    && cronTasks.get(tt.getTaskId()).getExpression().equals(expression)) {
                continue;
            }
            //如果策略执行时间发生了变化,则取消当前策略的任务
            if (scheduledFutures.containsKey(tt.getTaskId())) {
                scheduledFutures.remove(tt.getTaskId()).cancel(false);
                cronTasks.remove(tt.getTaskId());
            }
            //创建真实的定时任务
            CronTask task = new CronTask(tt, expression);
            /**
             * TaskScheduler  = registrar.getScheduler() 得到任务调度器
             * ScheduledFuture<?> future = TaskScheduler.schedule(Runnable task, Date startTime) 安排给定的Runnable,在指定的执行时间调用它,也就是执行TimingTask的run方法内容
             *
             * task:真实的定时任务 future:真实的定时任务执行者
             * 【task到future还需要触发】
             */
            ScheduledFuture<?> future = registrar.getScheduler().schedule(task.getRunnable(), task.getTrigger());
            //分别存放到集合中去
            cronTasks.put(tt.getTaskId(), task);
            scheduledFutures.put(tt.getTaskId(), future);
        }
    }

    /**
     * 判断定时任务是否存在
     * @param tasks 任务
     * @param taskId 任务id
     * @return
     */
    private boolean exists(List<TimingTask> tasks, String taskId) {
        for (TimingTask task : tasks) {
            if (task.getTaskId().equals(taskId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 销毁当前系统中正在运行的所有定时任务
     */
    @PreDestroy
    public void destroy() {
        this.registrar.destroy();
    }

    /**
     * 自定义任务对象,存储taskId和cron表达式,由业务层调用传入
     */
    public static class TaskConstant {
        private String cron;
        private String taskId;

        public String getCron() {
            return cron;
        }

        public void setCron(String cron) {
            this.cron = cron;
        }

        public String getTaskId() {
            return taskId;
        }

        public void setTaskId(String taskId) {
            this.taskId = taskId;
        }
    }

    /**
     * 也算是一个定时任务吧(汗。。强行解释)
     * 是更新后的定时任务,实质上和上面一样,只不过作用的时间段有区别,前者在检测动态定时任务列表之前,后者在检测动态定时任务列表之后
     *
     * 定时任务就是一个异步线程对象(Runnable) And 定时Trigger
     * 实现Runable,为创建真实的定时任务CronTask做准备
     */
    private class TimingTask implements Runnable {
        private String expression;

        private String taskId;

        public String getTaskId() {
            return taskId;
        }

        public void setTaskId(String taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            //############# 定时任务的业务逻辑 BEGIN ###############
            String taskId = this.getTaskId();
            CronInfo cronInfo = cronInfoService.getById(taskId);
            if(cronInfo == null){
                throw new RuntimeException("任务不存在");
            }
            ServiceInfo serviceInfo = serviceInfoService.getById(cronInfo.getServiceId());
            String url = serviceInfo.getServiceIp() + cronInfo.getCronUri();
            HttpUtil.sendGet(url,null);

            //############# 定时任务的业务逻辑 END ###############
        }

        public String getExpression() {
            return expression;
        }

        public void setExpression(String expression) {
            this.expression = expression;
        }

        @Override
        public String toString() {
            return ReflectionToStringBuilder.toString(this
                    , ToStringStyle.JSON_STYLE
                    , false
                    , false
                    , TimingTask.class);
        }

    }

    /**
     * 队列消费线程工厂类
     */
    private static class DynamicTaskConsumeThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DynamicTaskConsumeThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                    poolNumber.getAndIncrement() +
                    "-dynamic-task-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }

}

五,com.dayouzc.cronjob.constant

public class Constants {
    /** 状态 */
    public static final class StatusConstant {
        public static final String NORMAL = "1";
        public static final String DELETED = "0";
        public static Map<String, String> map = new LinkedHashMap<String, String>() {
            {
                put("1", "正常");
                put("0", "已删除");
            }
        };
    }
    /** 定时任务状态 */
    public static final class CronConstant {
        /** 已开启 */
        public static final String STARTED = "1";
        /** 已停止 */
        public static final String STOPED = "2";
        public static Map<String, String> map = new LinkedHashMap<String, String>() {
            {
                put("1", "已开启");
                put("2", "已停止");
            }
        };
    }
}

六,com.dayouzc.cronjob.controller

@RestController
@RequestMapping("/cronInfo")
public class CronInfoController {

    @Autowired
    private CronInfoService cronInfoService;
    @Autowired
    private DynamicTask dynamicTask;

    /**
     * 查询定时任务列表
     * @param cronInfo
     * @return
     */
    @GetMapping("/all")
    public ResponseData<List<CronInfo>> queryCrons(CronInfo cronInfo){
        //1,校验
        //2,业务处理
        cronInfo.setStatus(Constants.StatusConstant.NORMAL);
        List<CronInfo> cronInfos = cronInfoService.queryCronInfos(cronInfo);
        //3,响应
        ResponseData<List<CronInfo>> listResponseData = new ResponseData<>();
        listResponseData.setResult(cronInfos);
        return listResponseData;
    }

    /**
     * 新增定时任务
     * @param cronInfo
     * @return
     */
    @PostMapping("/add")
    public ResponseData addCron(CronInfo cronInfo){
        //1,校验
        //2,业务处理
        cronInfoService.addCronInfo(cronInfo);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public ResponseData getById(String id){
        //1,校验
        //2,业务处理
        CronInfo cronInfo = cronInfoService.getById(id);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        responseData.setResult(cronInfo);
        return responseData;
    }

    /**
     * 编辑
     * @param cronInfo
     * @return
     */
    @PostMapping("/update")
    public ResponseData edit(CronInfo cronInfo){
        //1,校验
        //2,业务处理
        CronInfo cronInfo1 = cronInfoService.getById(cronInfo.getCronId());
        cronInfo.setCronStatus(cronInfo1.getCronStatus());
        cronInfoService.updateCronInfo(cronInfo);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResponseData del(String id){
        //1,校验
        CronInfo cronInfo = cronInfoService.getById(id);
        if(Constants.CronConstant.STARTED.equals(cronInfo.getCronStatus())){
            return new ResponseData("500","此任务正在运行,需要先终止该任务后方可删除");
        }
        //2,业务处理
        cronInfoService.delCronInfo(id);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
    /**
     * 开启定时任务
     * @param id
     * @return
     */
    @GetMapping("/start")
    public ResponseData start(String id){

        //1,校验
        //2,业务处理
        CronInfo cronInfo = cronInfoService.getById(id);
        cronInfo.setCronStatus(Constants.CronConstant.STARTED);
        cronInfoService.updateCronInfo(cronInfo);
        //动态开启定时任务
        dynamicTask.startTask(cronInfo.getCronId(),cronInfo.getCronExpression());
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
    /**
     * 停止定时任务
     * @param id
     * @return
     */
    @GetMapping("/stop")
    public ResponseData stop(String id){
        //1,校验
        //2,业务处理
        CronInfo cronInfo = cronInfoService.getById(id);
        cronInfo.setCronStatus(Constants.CronConstant.STOPED);
        cronInfoService.updateCronInfo(cronInfo);
        //动态停止定时任务
        dynamicTask.stopTaskByTaskId(cronInfo.getCronId());
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
}
@RestController
@RequestMapping("/serviceInfo")
public class ServiceInfoController {

    @Autowired
    private ServiceInfoService serviceInfoService;

    /**
     * 查询服务器列表
     * @param cronInfo
     * @return
     */
    @GetMapping("/all")
    public ResponseData<List<ServiceInfo>> queryCrons(ServiceInfo cronInfo){
        //1,校验
        //2,业务处理
        cronInfo.setStatus(Constants.StatusConstant.NORMAL);
        List<ServiceInfo> cronInfos = serviceInfoService.queryServiceInfos(cronInfo);
        //3,响应
        ResponseData<List<ServiceInfo>> listResponseData = new ResponseData<>();
        listResponseData.setResult(cronInfos);
        return listResponseData;
    }

    /**
     * 新增服务器
     * @param cronInfo
     * @return
     */
    @PostMapping("/add")
    public ResponseData addCron(ServiceInfo cronInfo){
        //1,校验
        //2,业务处理
        serviceInfoService.addServiceInfo(cronInfo);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public ResponseData getById(String id){
        //1,校验
        //2,业务处理
        ServiceInfo cronInfo = serviceInfoService.getById(id);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        responseData.setResult(cronInfo);
        return responseData;
    }

    /**
     * 编辑
     * @param cronInfo
     * @return
     */
    @PostMapping("/update")
    public ResponseData edit(ServiceInfo cronInfo){
        //1,校验
        //2,业务处理
        serviceInfoService.updateServiceInfo(cronInfo);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResponseData del(String id){
        //1,校验
        //2,业务处理
        serviceInfoService.delServiceInfo(id);
        //3,响应
        ResponseData responseData = new ResponseData<>();
        return responseData;
    }
}

七,com.dayouzc.cronjob.service

public interface CronInfoService {

    /**
     * 查询定时任务列表
     */
    List<CronInfo> queryCronInfos(CronInfo cronInfo);
    /**
     * 新增定时任务
     */
    int addCronInfo(CronInfo cronInfo);
    /**
     * 根据id查询
     */
    CronInfo getById(String id);
    /**
     * 编辑
     */
    int updateCronInfo(CronInfo cronInfo);
    /**
     * 删除
     */
    int delCronInfo(String id);
}
@Service
public class CronInfoServiceImpl implements CronInfoService {

    @Autowired
    private CronInfoMapper cronInfoMapper;

    @Override
    public List<CronInfo> queryCronInfos(CronInfo cronInfo) {
        return cronInfoMapper.queryCronInfos(cronInfo);
    }

    @Override
    public int addCronInfo(CronInfo cronInfo) {
        cronInfo.setCronId(UUIDUtil.getUUID());
        cronInfo.setCronStatus(Constants.CronConstant.STOPED);
        cronInfo.setCreateTime(new Date());
        cronInfo.setUpdateTime(null);
        return cronInfoMapper.addCronInfos(cronInfo);
    }

    @Override
    public CronInfo getById(String id) {
        return cronInfoMapper.getById(id);
    }

    @Override
    public int updateCronInfo(CronInfo cronInfo) {
        cronInfo.setUpdateTime(new Date());
        return cronInfoMapper.updateCronInfo(cronInfo);
    }

    @Override
    public int delCronInfo(String id) {
        return cronInfoMapper.delCronInfo(id);
    }
}
public interface ServiceInfoService {

    /**
     * 查询服务器列表
     */
    List<ServiceInfo> queryServiceInfos(ServiceInfo cronInfo);
    /**
     * 新增服务器
     */
    int addServiceInfo(ServiceInfo cronInfo);
    /**
     * 根据id查询
     */
    ServiceInfo getById(String id);
    /**
     * 编辑
     */
    int updateServiceInfo(ServiceInfo cronInfo);
    /**
     * 删除
     */
    int delServiceInfo(String id);
}
@Service
public class ServiceInfoServiceImpl implements ServiceInfoService {

    @Autowired
    private ServiceInfoMapper serviceInfoMapper;


    @Override
    public List<ServiceInfo> queryServiceInfos(ServiceInfo cronInfo) {
        return serviceInfoMapper.queryServiceInfos(cronInfo);
    }

    @Override
    public int addServiceInfo(ServiceInfo cronInfo) {
        cronInfo.setServiceId(UUIDUtil.getUUID());
        cronInfo.setCreateTime(new Date());
        cronInfo.setUpdateTime(null);
        return serviceInfoMapper.addServiceInfos(cronInfo);
    }

    @Override
    public ServiceInfo getById(String id) {
        return serviceInfoMapper.getById(id);
    }

    @Override
    public int updateServiceInfo(ServiceInfo cronInfo) {
        cronInfo.setUpdateTime(new Date());
        return serviceInfoMapper.updateServiceInfo(cronInfo);
    }

    @Override
    public int delServiceInfo(String id) {
        return serviceInfoMapper.delServiceInfo(id);
    }
}

八,com.dayouzc.cronjob.mapper

@Mapper
@Repository
public interface CronInfoMapper {
    /**
     * 查询定时任务列表
     */
    @Select("select a.*,b.service_name as serviceName from cron_info a,service_info b where a.service_id=b.service_id and a.status = #{cronInfo.status} order by a.create_time desc")
    @Results({
            @Result(id=true,property="cronId",column="cron_id"),
            @Result(property="serviceId",column="service_id"),
            @Result(property="cronName",column="cron_name"),
            @Result(property="cronExpression",column="cron_expression"),
            @Result(property="cronUri",column="cron_uri"),
            @Result(property="cronStatus",column="cron_status"),
            @Result(property="createTime",column="create_time"),
            @Result(property="updateTime",column="update_time"),
            @Result(property="status",column="status"),
            @Result(property="memo",column="memo")
    })
    List<CronInfo> queryCronInfos(@Param("cronInfo") CronInfo cronInfo);

    /**
     * 新增定时任务
     */
    @Insert("insert into cron_info values(#{cronInfo.cronId},#{cronInfo.serviceId},#{cronInfo.cronName},#{cronInfo.cronExpression}," +
            "#{cronInfo.cronUri},#{cronInfo.cronStatus},#{cronInfo.createTime},#{cronInfo.updateTime},1,#{cronInfo.memo})")
    int addCronInfos(@Param("cronInfo") CronInfo cronInfo);

    /**
     * 根据id查询任务
     */
    @Select("select * from cron_info where cron_id = #{id}")
    @Results({
            @Result(id=true,property="cronId",column="cron_id"),
            @Result(property="serviceId",column="service_id"),
            @Result(property="cronName",column="cron_name"),
            @Result(property="cronExpression",column="cron_expression"),
            @Result(property="cronUri",column="cron_uri"),
            @Result(property="cronStatus",column="cron_status"),
            @Result(property="createTime",column="create_time"),
            @Result(property="updateTime",column="update_time"),
            @Result(property="status",column="status"),
            @Result(property="memo",column="memo")
    })
    CronInfo getById(@Param("id") String id);

    /**
     * 编辑
     */
    @Update("update cron_info set service_id=#{cronInfo.serviceId},cron_name=#{cronInfo.cronName},cron_expression=#{cronInfo.cronExpression}," +
            "cron_uri=#{cronInfo.cronUri},cron_status=#{cronInfo.cronStatus},update_time=#{cronInfo.updateTime},memo=#{cronInfo.memo} " +
            "where cron_id=#{cronInfo.cronId}")
    int updateCronInfo(@Param("cronInfo") CronInfo cronInfo);

    /**
     * 删除
     */
    @Update("update cron_info set status = '0' where cron_id=#{id}")
    int delCronInfo(@Param("id") String id);
}
@Mapper
@Repository
public interface ServiceInfoMapper {
    /**
     * 查询服务器列表
     */
    @Select("select a.* from service_info a where a.status = #{serviceInfo.status} order by a.create_time desc")
    @Results({
            @Result(id=true,property="serviceId",column="service_id"),
            @Result(property="serviceName",column="service_name"),
            @Result(property="serviceIp",column="service_ip"),
            @Result(property="servicePort",column="service_port"),
            @Result(property="createTime",column="create_time"),
            @Result(property="updateTime",column="update_time"),
            @Result(property="status",column="status")
    })
    List<ServiceInfo> queryServiceInfos(@Param("serviceInfo") ServiceInfo serviceInfo);

    /**
     * 新增服务器
     */
    @Insert("insert into service_info values(#{serviceInfo.serviceId},#{serviceInfo.serviceName},#{serviceInfo.serviceIp},#{serviceInfo.servicePort}," +
            "#{serviceInfo.createTime},#{serviceInfo.updateTime},1)")
    int addServiceInfos(@Param("serviceInfo") ServiceInfo serviceInfo);

    /**
     * 根据id查询服务器
     */
    @Select("select * from service_info where service_id = #{id}")
    @Results({
            @Result(id=true,property="serviceId",column="service_id"),
            @Result(property="serviceName",column="service_name"),
            @Result(property="serviceIp",column="service_ip"),
            @Result(property="servicePort",column="service_port"),
            @Result(property="createTime",column="create_time"),
            @Result(property="updateTime",column="update_time"),
            @Result(property="status",column="status")
    })
    ServiceInfo getById(@Param("id") String id);

    /**
     * 编辑
     */
    @Update("update service_info set " +
            "service_name=#{serviceInfo.serviceName}," +
            "service_ip=#{serviceInfo.serviceIp}," +
            "service_port=#{serviceInfo.servicePort}," +
            "update_time=#{serviceInfo.updateTime} " +
            "where service_id=#{serviceInfo.serviceId}")
    int updateServiceInfo(@Param("serviceInfo") ServiceInfo serviceInfo);

    /**
     * 删除
     */
    @Update("update service_info set status = '0' where service_id=#{id}")
    int delServiceInfo(@Param("id") String id);
}

九,com.dayouzc.cronjob.model

public class CronInfo {
    /**
     * 主键
     */
    private String cronId;
    /**
     * 服务器id
     */
    private String serviceId;
    /**
     * 服务器名称
     */
    private String serviceName;
    /**
     * 定时任务名称
     */
    private String cronName;
    /**
     * 正则表达式
     */
    private String cronExpression;
    /**
     * 定时任务执行的逻辑接口uri
     */
    private String cronUri;
    /**
     * 定时任务状态 1:已开启  2:已停止
     */
    private String cronStatus;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
    /**
     * 状态 1:正常  0:删除
     */
    private String status;
    /**
     * 备注
     */
    private String memo;
}
public class ServiceInfo {
    /**
     * 主键
     */
    private String serviceId;
    /**
     * 服务器名称
     */
    private String serviceName;
    /**
     * 服务器ip地址
     */
    private String serviceIp;
    /**
     * 服务器端口号
     */
    private String servicePort;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
    /**
     * 状态 1:正常  0:删除
     */
    private String status;
}

标签:return,String,系统,public,cron,引擎,cronInfo,任务调度,id
来源: https://www.cnblogs.com/fantongxue/p/16469829.html