关于java:Spring-Boot-定时任务怎么实现任务动态增删启停

7次阅读

共计 9039 个字符,预计需要花费 23 分钟才能阅读完成。

作者:jessehua

链接:https://www.jianshu.com/p/0f6…

在 spring boot 我的项目中,能够通过 @EnableScheduling 注解和 @Scheduled 注解实现定时工作,也能够通过 SchedulingConfigurer 接口来实现定时工作。然而这两种形式不能动静增加、删除、启动、进行工作。要实现动静增删启停定时工作性能,比拟宽泛的做法是集成 Quartz 框架。

然而自己的开发准则是:在满足我的项目需要的状况下,尽量少的依赖其它框架,防止我的项目过于臃肿和简单。查看 spring-context 这个 jar 包中 org.springframework.scheduling.ScheduledTaskRegistrar 这个类的源代码,发现能够通过革新这个类就能实现动静增删启停定时工作性能。

Spring Boot 根底就不介绍了,举荐下这个实战教程:
https://github.com/javastacks…

增加执行定时工作的线程池配置类

@Configuration
public class SchedulingConfig {
    @Bean
    public TaskScheduler taskScheduler() {ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 定时工作执行线程池外围线程数
        taskScheduler.setPoolSize(4);
        taskScheduler.setRemoveOnCancelPolicy(true);
        taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
        return taskScheduler;
    }
}

增加 ScheduledFuture 的包装类。ScheduledFuture 是 ScheduledExecutorService 定时工作线程池的执行后果。

public final class ScheduledTask {

    volatile ScheduledFuture<?> future;

    /**
     * 勾销定时工作
     */
    public void cancel() {
        ScheduledFuture<?> future = this.future;
        if (future != null) {future.cancel(true);
        }
    }
}

增加 Runnable 接口实现类,被定时工作线程池调用,用来执行指定 bean 外面的办法。

public class SchedulingRunnable implements Runnable {private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class);

    private String beanName;

    private String methodName;

    private String params;

    public SchedulingRunnable(String beanName, String methodName) {this(beanName, methodName, null);
    }

    public SchedulingRunnable(String beanName, String methodName, String params) {
        this.beanName = beanName;
        this.methodName = methodName;
        this.params = params;
    }

    @Override
    public void run() {logger.info("定时工作开始执行 - bean:{},办法:{},参数:{}", beanName, methodName, params);
        long startTime = System.currentTimeMillis();

        try {Object target = SpringContextUtils.getBean(beanName);

            Method method = null;
            if (StringUtils.isNotEmpty(params)) {method = target.getClass().getDeclaredMethod(methodName, String.class);
            } else {method = target.getClass().getDeclaredMethod(methodName);
            }

            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isNotEmpty(params)) {method.invoke(target, params);
            } else {method.invoke(target);
            }
        } catch (Exception ex) {logger.error(String.format("定时工作执行异样 - bean:%s,办法:%s,参数:%s", beanName, methodName, params), ex);
        }

        long times = System.currentTimeMillis() - startTime;
        logger.info("定时工作执行完结 - bean:{},办法:{},参数:{},耗时:{} 毫秒", beanName, methodName, params, times);
    }

    @Override
    public boolean equals(Object o) {if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SchedulingRunnable that = (SchedulingRunnable) o;
        if (params == null) {return beanName.equals(that.beanName) &&
                    methodName.equals(that.methodName) &&
                    that.params == null;
        }

        return beanName.equals(that.beanName) &&
                methodName.equals(that.methodName) &&
                params.equals(that.params);
    }

    @Override
    public int hashCode() {if (params == null) {return Objects.hash(beanName, methodName);
        }

        return Objects.hash(beanName, methodName, params);
    }
}

增加定时工作注册类,用来减少、删除定时工作。

@Component
public class CronTaskRegistrar implements DisposableBean {private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getScheduler() {return this.taskScheduler;}

    public void addCronTask(Runnable task, String cronExpression) {addCronTask(new CronTask(task, cronExpression));
    }

    public void addCronTask(CronTask cronTask) {if (cronTask != null) {Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {removeCronTask(task);
            }

            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }

    public void removeCronTask(Runnable task) {ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
        if (scheduledTask != null)
            scheduledTask.cancel();}

    public ScheduledTask scheduleCronTask(CronTask cronTask) {ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());

        return scheduledTask;
    }


    @Override
    public void destroy() {for (ScheduledTask task : this.scheduledTasks.values()) {task.cancel();
        }

        this.scheduledTasks.clear();}
}

增加定时工作示例类

@Component("demoTask")
public class DemoTask {public void taskWithParams(String params) {System.out.println("执行有参示例工作:" + params);
    }

    public void taskNoParams() {System.out.println("执行无参示例工作");
    }
}

定时工作数据库表设计

增加定时工作实体类

public class SysJobPO {
    /**
     * 工作 ID
     */
    private Integer jobId;
    /**
     * bean 名称
     */
    private String beanName;
    /**
     * 办法名称
     */
    private String methodName;
    /**
     * 办法参数
     */
    private String methodParams;
    /**
     * cron 表达式
     */
    private String cronExpression;
    /**
     * 状态(1 失常 0 暂停)*/
    private Integer jobStatus;
    /**
     * 备注
     */
    private String remark;
    /**
     * 创立工夫
     */
    private Date createTime;
    /**
     * 更新工夫
     */
    private Date updateTime;

    public Integer getJobId() {return jobId;}

    public void setJobId(Integer jobId) {this.jobId = jobId;}

    public String getBeanName() {return beanName;}

    public void setBeanName(String beanName) {this.beanName = beanName;}

    public String getMethodName() {return methodName;}

    public void setMethodName(String methodName) {this.methodName = methodName;}

    public String getMethodParams() {return methodParams;}

    public void setMethodParams(String methodParams) {this.methodParams = methodParams;}

    public String getCronExpression() {return cronExpression;}

    public void setCronExpression(String cronExpression) {this.cronExpression = cronExpression;}

    public Integer getJobStatus() {return jobStatus;}

    public void setJobStatus(Integer jobStatus) {this.jobStatus = jobStatus;}

    public String getRemark() {return remark;}

    public void setRemark(String remark) {this.remark = remark;}

    public Date getCreateTime() {return createTime;}

    public void setCreateTime(Date createTime) {this.createTime = createTime;}

    public Date getUpdateTime() {return updateTime;}

    public void setUpdateTime(Date updateTime) {this.updateTime = updateTime;}

}

新增定时工作

新增定时工作

boolean success = sysJobRepository.addSysJob(sysJob);
if (!success)
    return OperationResUtils.fail("新增失败");
else {if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
        cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
    }
}

return OperationResUtils.success();

批改定时工作,先移除原来的工作,再启动新工作

boolean success = sysJobRepository.editSysJob(sysJob);
if (!success)
    return OperationResUtils.fail("编辑失败");
else {
    // 先移除再增加
    if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
        cronTaskRegistrar.removeCronTask(task);
    }

    if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
        cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
    }
}

return OperationResUtils.success();

删除定时工作

boolean success = sysJobRepository.deleteSysJobById(req.getJobId());
if (!success)
    return OperationResUtils.fail("删除失败");
else{if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
        cronTaskRegistrar.removeCronTask(task);
    }
}

return OperationResUtils.success();

定时工作启动 / 进行状态切换

if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
    cronTaskRegistrar.addCronTask(task, existedSysJob.getCronExpression());
} else {SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
    cronTaskRegistrar.removeCronTask(task);
}

增加实现了 CommandLineRunner 接口的 SysJobRunner 类,当 spring boot 我的项目启动实现后,加载数据库里状态为失常的定时工作。

@Service
public class SysJobRunner implements CommandLineRunner {private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);

    @Autowired
    private ISysJobRepository sysJobRepository;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为失常的定时工作
        List<SysJobPO> jobList = sysJobRepository.getSysJobListByStatus(SysJobStatus.NORMAL.ordinal());
        if (CollectionUtils.isNotEmpty(jobList)) {for (SysJobPO job : jobList) {SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }

            logger.info("定时工作已加载结束...");
        }
    }
}

工具类 SpringContextUtils,用来从 spring 容器里获取 bean

@Component
public class SpringContextUtils implements ApplicationContextAware {

    private 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(Class<T> requiredType) {return applicationContext.getBean(requiredType);
    }

    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);
    }
}

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿 (2021 最新版)

2. 别在再满屏的 if/ else 了,试试策略模式,真香!!

3. 卧槽!Java 中的 xx ≠ null 是什么新语法?

4.Spring Boot 2.5 重磅公布,光明模式太炸了!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0