Java task类需要自己销毁_Spring内置任务调度如何实现添加、取消与重置详解

前言

大家应该都有所体会,使用Spring的任务调度给我们的开发带来了极大的便利,不过当我们的任务调度配置完成后,很难再对其进行更改,除非停止服务器,修改配置,然后再重启,显然这样是不利于线上操作的,为了实现动态的任务调度修改,我在网上也查阅了一些资料,大部分都是基于quartz实现的,使用Spring内置的任务调度则少之又少,而且效果不理想,需要在下次任务执行后,新的配置才能生效,做不到立即生效。本着探索研究的原则,查看了一下Spring的源码,下面为大家提供一种Spring内置任务调度实现添加、取消、重置的方法。话不多说了,来一起看看详细的介绍 吧。

实现方法如下

首先,我们需要启用Spring的任务调度

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:task="http://www.springframework.org/schema/task"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.2.xsd">

这一部分配置在网上是很常见的,接下来我们需要联合使用@EnableScheduling与org.springframework.scheduling.annotation.SchedulingConfigurer便携我们自己的调度配置,在SchedulingConfigurer接口中,需要实现一个void configureTasks(ScheduledTaskRegistrar taskRegistrar);方法,传统做法是在该方法中添加需要执行的调度信息。网上的基本撒谎那个也都是使用该方法实现的,使用addTriggerTask添加任务,并结合cron表达式动态修改调度时间,这里我们并不这样做。

查看一下ScheduledTaskRegistrar源码,我们发现该对象初始化完成后会执行scheduleTasks()方法,在该方法中添加任务调度信息,最终所有的任务信息都存放在名为scheduledFutures的集合中。

protected void scheduleTasks() {

long now = System.currentTimeMillis();

if (this.taskScheduler == null) {

this.localExecutor = Executors.newSingleThreadScheduledExecutor();

this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);

}

if (this.triggerTasks != null) {

for (TriggerTask task : this.triggerTasks) {

this.scheduledFutures.add(this.taskScheduler.schedule(

task.getRunnable(), task.getTrigger()));

}

}

if (this.cronTasks != null) {

for (CronTask task : this.cronTasks) {

this.scheduledFutures.add(this.taskScheduler.schedule(

task.getRunnable(), task.getTrigger()));

}

}

if (this.fixedRateTasks != null) {

for (IntervalTask task : this.fixedRateTasks) {

if (task.getInitialDelay() > 0) {

Date startTime = new Date(now + task.getInitialDelay());

this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(

task.getRunnable(), startTime, task.getInterval()));

}

else {

this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(

task.getRunnable(), task.getInterval()));

}

}

}

if (

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值