简版调度中心搭建及实现思路

2018-01-21  本文已影响0人  master_h
前言
项目架构
搭建配置
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>仓库最高版本号</version>
</dependency>

其他mysql依赖忽略

    @Bean
    @Order(0)
    public Scheduler quartzTask() {
        Scheduler scheduler = new Scheduler();
        scheduler.setDaemon(true);
        scheduler.setMatchSecond(true);
        return scheduler;
    }
@Configuration
@Order(1)
@Slf4j
public class QuartzJobs {


    @Autowired(required = false)
    private Scheduler scheduler;

    @Autowired(required = false)
    private QuartzDetailsService quartzDetailsService;


    /**
     * 每间隔5秒钟从数据库钟查询任务并添加到调度队列中
     *
     * @throws MalformedURLException
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @Scheduled(fixedDelay = 30000)
    public void queueJobs() {

        //从task表中查询新增加的任务信息
        List<QuartzDetails> jobDetails = quartzDetailsService.selectList(new EntityWrapper<QuartzDetails>().eq("job_enable", 1).eq("job_add_flag", 0));
        if (jobDetails != null && !jobDetails.isEmpty()) {
            jobDetails.forEach((QuartzDetails job) -> {
                try {
                    URL url = new URL("file:" + job.getJobPath());
                    URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
                    Class<?> clazz = urlClassLoader.loadClass(job.getJobMain());
                    Runnable runnable = (Runnable) clazz.newInstance();
                    scheduler.schedule(job.getJobId(), job.getJobCorn(), runnable);
                    log.warn("新增jod : {} 成功", job.getJobId());
                    job.setJobAddFlag(1);
                    quartzDetailsService.update(job, new EntityWrapper<QuartzDetails>().eq("job_id", job.getJobId()));
                } catch (CronException cron) {
                    log.warn("该任务已添加过,请勿重复添加调度task:{}", cron);
                } catch (IllegalAccessException | InstantiationException | ClassNotFoundException | MalformedURLException e) {
                    log.error("添加任务失败:{}", e);
                }

            });
            if (!scheduler.isStarted()) {
                scheduler.start();
            }
        }


    }

    /**
     * 每次间隔30秒钟检测一次当前调度是否存活
     */
    @Scheduled(fixedRate = 30000)
    public void removeQueueJobs() {
        //从task表中查询需移除的任务信息
        List<QuartzDetails> jobDetails = quartzDetailsService.selectList(new EntityWrapper<QuartzDetails>().eq("job_enable", 0).eq("job_add_flag", 1));
        jobDetails.forEach(job -> {
            if (scheduler.isStarted()) {
                scheduler.deschedule(job.getJobId());
                log.warn("移除task任务 : {} 成功", job.getJobId());
                job.setJobAddFlag(0);
                quartzDetailsService.update(job, new EntityWrapper<QuartzDetails>().eq("job_id", job.getJobId()));
            }
        });

    }

}
| juncai_quartz_details | CREATE TABLE `juncai_quartz_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `job_id` varchar(20) NOT NULL COMMENT '任务名称',
  `job_path` varchar(200) NOT NULL COMMENT '任务地址(绝对路径)',
  `job_main` varchar(100) NOT NULL COMMENT '执行run路径',
  `job_enable` tinyint(4) NOT NULL DEFAULT '1' COMMENT '默认为1启用 否则为暂停',
  `job_add_flag` tinyint(4) DEFAULT '0' COMMENT '是否添加到调度队列标识 0未添加 否则为添加',
  `job_corn` varchar(50) NOT NULL COMMENT '执行表达式',
  `job_ip` varchar(20) DEFAULT NULL COMMENT '任务所在机器地址',
  `job_id_log` varchar(50) DEFAULT NULL COMMENT '任务日志名称',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8              
@Slf4j
public class QueryZcmlcLoan implements Runnable{

    @Override
    public void run() {
        log.warn("开始查询.");
        System.out.println("hello world!");
        log.warn("查询task结束.");
    }
}

如有疑问或者问题请留言,thanks

上一篇下一篇

猜你喜欢

热点阅读