Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 任务调度动态改变时间
不需要重启应用就可以动态的改变Cron表达式的值
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component; @Lazy(false)
@Component
@EnableScheduling
public class DynamicScheduledTask implements SchedulingConfigurer { /**
* 通过自动注入启动任务调度
*
* @Autowired
* DynamicScheduledTask dynamicScheduledTask;
*
*/ private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String DEFAULT_CRON = "0 0/10 * * * ? ";
private String cron = DEFAULT_CRON; /**
* 获取任务执行规则
* @return
*/
public String getCron() {
return cron;
} /**
* 设置任务执行规则
* @param cron
*/
public void setCron(String cron) {
this.cron = cron;
} @Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool();
} @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//用于设置定时任务线程数,默认不设置的话为单线程
taskRegistrar.setScheduler(taskExecutor());
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
// 任务逻辑
logger.debug("dynamicCronTask is running...");
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(cron);
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
}
});
}
}
关键说明
taskRegistrar.setScheduler(taskExecutor());
//用于设置定时任务线程数,默认不设置的话为单线程,当存在多个任务调度的时候,如果不设置此代码,如果有任务调度在运行时其他任务则被堵塞
ScheduledTaskRegistrar 代码分析
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.scheduling.config; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; /**
* Helper bean for registering tasks with a {@link TaskScheduler}, typically using cron
* expressions.
*
* <p>As of Spring 3.1, {@code ScheduledTaskRegistrar} has a more prominent user-facing
* role when used in conjunction with the @{@link
* org.springframework.scheduling.annotation.EnableAsync EnableAsync} annotation and its
* {@link org.springframework.scheduling.annotation.SchedulingConfigurer
* SchedulingConfigurer} callback interface.
*
* @author Juergen Hoeller
* @author Chris Beams
* @author Tobias Montagna-Hay
* @since 3.0
* @see org.springframework.scheduling.annotation.EnableAsync
* @see org.springframework.scheduling.annotation.SchedulingConfigurer
*/
public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean { private TaskScheduler taskScheduler; private ScheduledExecutorService localExecutor; private List<TriggerTask> triggerTasks; private List<CronTask> cronTasks; private List<IntervalTask> fixedRateTasks; private List<IntervalTask> fixedDelayTasks; private final Set<ScheduledFuture<?>> scheduledFutures = new LinkedHashSet<ScheduledFuture<?>>(); /**
* Set the {@link TaskScheduler} to register scheduled tasks with.
*/
public void setTaskScheduler(TaskScheduler taskScheduler) {
Assert.notNull(taskScheduler, "TaskScheduler must not be null");
this.taskScheduler = taskScheduler;
} /**
* Set the {@link TaskScheduler} to register scheduled tasks with, or a
* {@link java.util.concurrent.ScheduledExecutorService} to be wrapped as a
* {@code TaskScheduler}.
*/
public void setScheduler(Object scheduler) {
Assert.notNull(scheduler, "Scheduler object must not be null");
if (scheduler instanceof TaskScheduler) {
this.taskScheduler = (TaskScheduler) scheduler;
}
else if (scheduler instanceof ScheduledExecutorService) {
this.taskScheduler = new ConcurrentTaskScheduler(((ScheduledExecutorService) scheduler));
}
else {
throw new IllegalArgumentException("Unsupported scheduler type: " + scheduler.getClass());
}
} /**
* Return the {@link TaskScheduler} instance for this registrar (may be {@code null}).
*/
public TaskScheduler getScheduler() {
return this.taskScheduler;
} /**
* Specify triggered tasks as a Map of Runnables (the tasks) and Trigger objects
* (typically custom implementations of the {@link Trigger} interface).
*/
public void setTriggerTasks(Map<Runnable, Trigger> triggerTasks) {
this.triggerTasks = new ArrayList<TriggerTask>();
for (Map.Entry<Runnable, Trigger> task : triggerTasks.entrySet()) {
addTriggerTask(new TriggerTask(task.getKey(), task.getValue()));
}
} /**
* Specify triggered tasks as a list of {@link TriggerTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setTriggerTasksList(List<TriggerTask> triggerTasks) {
this.triggerTasks = triggerTasks;
} /**
* Get the trigger tasks as an unmodifiable list of {@link TriggerTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<TriggerTask> getTriggerTaskList() {
return (this.triggerTasks != null? Collections.unmodifiableList(this.triggerTasks) :
Collections.<TriggerTask>emptyList());
} /**
* Specify triggered tasks as a Map of Runnables (the tasks) and cron expressions.
* @see CronTrigger
*/
public void setCronTasks(Map<Runnable, String> cronTasks) {
this.cronTasks = new ArrayList<CronTask>();
for (Map.Entry<Runnable, String> task : cronTasks.entrySet()) {
addCronTask(task.getKey(), task.getValue());
}
} /**
* Specify triggered tasks as a list of {@link CronTask} objects. Primarily used by
* {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setCronTasksList(List<CronTask> cronTasks) {
this.cronTasks = cronTasks;
} /**
* Get the cron tasks as an unmodifiable list of {@link CronTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<CronTask> getCronTaskList() {
return (this.cronTasks != null ? Collections.unmodifiableList(this.cronTasks) :
Collections.<CronTask>emptyList());
} /**
* Specify triggered tasks as a Map of Runnables (the tasks) and fixed-rate values.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void setFixedRateTasks(Map<Runnable, Long> fixedRateTasks) {
this.fixedRateTasks = new ArrayList<IntervalTask>();
for (Map.Entry<Runnable, Long> task : fixedRateTasks.entrySet()) {
addFixedRateTask(task.getKey(), task.getValue());
}
} /**
* Specify fixed-rate tasks as a list of {@link IntervalTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setFixedRateTasksList(List<IntervalTask> fixedRateTasks) {
this.fixedRateTasks = fixedRateTasks;
} /**
* Get the fixed-rate tasks as an unmodifiable list of {@link IntervalTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<IntervalTask> getFixedRateTaskList() {
return (this.fixedRateTasks != null ? Collections.unmodifiableList(this.fixedRateTasks) :
Collections.<IntervalTask>emptyList());
} /**
* Specify triggered tasks as a Map of Runnables (the tasks) and fixed-delay values.
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void setFixedDelayTasks(Map<Runnable, Long> fixedDelayTasks) {
this.fixedDelayTasks = new ArrayList<IntervalTask>();
for (Map.Entry<Runnable, Long> task : fixedDelayTasks.entrySet()) {
addFixedDelayTask(task.getKey(), task.getValue());
}
} /**
* Specify fixed-delay tasks as a list of {@link IntervalTask} objects. Primarily used
* by {@code <task:*>} namespace parsing.
* @since 3.2
* @see ScheduledTasksBeanDefinitionParser
*/
public void setFixedDelayTasksList(List<IntervalTask> fixedDelayTasks) {
this.fixedDelayTasks = fixedDelayTasks;
} /**
* Get the fixed-delay tasks as an unmodifiable list of {@link IntervalTask} objects.
* @return the list of tasks (never {@code null})
* @since 4.2
*/
public List<IntervalTask> getFixedDelayTaskList() {
return (this.fixedDelayTasks != null ? Collections.unmodifiableList(this.fixedDelayTasks) :
Collections.<IntervalTask>emptyList());
} /**
* Add a Runnable task to be triggered per the given {@link Trigger}.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addTriggerTask(Runnable task, Trigger trigger) {
addTriggerTask(new TriggerTask(task, trigger));
} /**
* Add a {@code TriggerTask}.
* @since 3.2
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addTriggerTask(TriggerTask task) {
if (this.triggerTasks == null) {
this.triggerTasks = new ArrayList<TriggerTask>();
}
this.triggerTasks.add(task);
} /**
* Add a Runnable task to be triggered per the given cron expression
*/
public void addCronTask(Runnable task, String expression) {
addCronTask(new CronTask(task, expression));
} /**
* Add a {@link CronTask}.
* @since 3.2
*/
public void addCronTask(CronTask task) {
if (this.cronTasks == null) {
this.cronTasks = new ArrayList<CronTask>();
}
this.cronTasks.add(task);
} /**
* Add a {@code Runnable} task to be triggered at the given fixed-rate interval.
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addFixedRateTask(Runnable task, long interval) {
addFixedRateTask(new IntervalTask(task, interval, ));
} /**
* Add a fixed-rate {@link IntervalTask}.
* @since 3.2
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
*/
public void addFixedRateTask(IntervalTask task) {
if (this.fixedRateTasks == null) {
this.fixedRateTasks = new ArrayList<IntervalTask>();
}
this.fixedRateTasks.add(task);
} /**
* Add a Runnable task to be triggered with the given fixed delay.
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void addFixedDelayTask(Runnable task, long delay) {
addFixedDelayTask(new IntervalTask(task, delay, ));
} /**
* Add a fixed-delay {@link IntervalTask}.
* @since 3.2
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
*/
public void addFixedDelayTask(IntervalTask task) {
if (this.fixedDelayTasks == null) {
this.fixedDelayTasks = new ArrayList<IntervalTask>();
}
this.fixedDelayTasks.add(task);
} /**
* Return whether this {@code ScheduledTaskRegistrar} has any tasks registered.
* @since 3.2
*/
public boolean hasTasks() {
return (!CollectionUtils.isEmpty(this.triggerTasks) ||
!CollectionUtils.isEmpty(this.cronTasks) ||
!CollectionUtils.isEmpty(this.fixedRateTasks) ||
!CollectionUtils.isEmpty(this.fixedDelayTasks));
} /**
* Calls {@link #scheduleTasks()} at bean construction time.
*/
@Override
public void afterPropertiesSet() {
scheduleTasks();
} /**
* Schedule all registered tasks against the underlying {@linkplain
* #setTaskScheduler(TaskScheduler) task scheduler}.
*/
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() > ) {
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 (this.fixedDelayTasks != null) {
for (IntervalTask task : this.fixedDelayTasks) {
if (task.getInitialDelay() > ) {
Date startTime = new Date(now + task.getInitialDelay());
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
task.getRunnable(), startTime, task.getInterval()));
}
else {
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
task.getRunnable(), task.getInterval()));
}
}
}
} @Override
public void destroy() {
for (ScheduledFuture<?> future : this.scheduledFutures) {
future.cancel(true);
}
if (this.localExecutor != null) {
this.localExecutor.shutdownNow();
}
} }
以上代码原至 spring 框架中
Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 任务调度动态改变时间的更多相关文章
- Spring 注解 @Scheduled(cron = "0 0/10 * * * ? ") 动态改变时间
import java.util.Date; import java.util.concurrent.Executor; import java.util.concurrent.Executors; ...
- spring注解 @Scheduled(cron = "0 0 1 * * *")实现定时的执行任务
@Scheduled(cron = "0 0 1 * * *") 在使用该注解以前请做好以下准备工作,配置好相应的xm文件. 配置定时注解的步骤:http://blog.csdn. ...
- spring注解scheduled实现定时任务
只想说,spring注解scheduled实现定时任务使用真的非常简单. 一.配置spring.xml文件 1.在beans加入xmlns:task="http://www.springfr ...
- Spring 计时器 @Scheduled cron 含义
Spring 计时器 @Scheduled cron 含义 学习:http://blog.csdn.net/prisonbreak_/article/details/49180307 http://b ...
- spring注解@Scheduled中fixedDelay、fixedRate和cron表达式的区别
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- Spring注解@Scheduled定时任务
一.首先配置applicationContext-task.xml (1)添加 xmlns:task="http://www.springframework.org/schema/task& ...
- Spring boot @Scheduled(cron = "* * * * * *") cron表达式详解
//@Scheduled(cron = "0 0/15 * * * ?") //每15分钟触发一次 //@Scheduled(cron = "5/10 * * * * ? ...
- spring 定时任务 scheduled Cron表达式
转载:https://blog.csdn.net/u011789653/article/details/51153536 可以借鉴:https://www.cnblogs.com/softidea/p ...
- Spring的定时任务@Scheduled(cron = "0 0 1 * * *")
指定某个方法在特定时间执行,如: cron="0 0 1 1 * ?" 即这个方法每月1号凌晨1点执行一次 关于这个注解的解释网上一大堆 但是今天遇到个问题,明明加了注解@Sche ...
随机推荐
- CentOS 7.1 中文正式版下载 - 最流行的免费开源企业级 Linux 服务器操作系统
如果说 Ubuntu 是现今最受桌面用户欢迎的 Linux 操作系统,那么 CentOS 就是最受公司.企业.IDC 喜爱的 Linux 发行版了.得益于极为出色的稳定性,全球范围内无数著名网站均选用 ...
- [CTSC2017]吉夫特(Lucas定理,DP)
送70分,预处理组合数是否为偶数即可. 剩下的数据,根据Lucas定理的推论可得当且仅当n&m=n的时候,C(n,m)为奇数.这样就可以直接DP了,对于每个数,考虑它对后面的数的影响即可,直接 ...
- Java下List<Long>转List<String>或者List<Long>转List<Integer>
说明:很遗憾,没有快速方法,只能遍历然后循环增加进去. 方法: for(String str : list) { int i = Integer.paseInt(str); intList.add(i ...
- 网络采集软件核心技术剖析系列(4)---使用C#语言如何将html网页转换成pdf(html2pdf)
一 本系列随笔概览及产生的背景 本系列开篇受到大家的热烈欢迎,这对博主是莫大的鼓励,此为本系列第四篇,希望大家继续支持,为我继续写作提供动力. 自己开发的豆约翰博客备份专家软件工具问世3年多以来,深受 ...
- SQL:将查询结果插入到另一个表的三种情况!
一:如果要插入目标表不存在: select * into 目标表 from 表 where ... 二:如果要插入目标表已经存在: insert into 目的表 select * from 表 wh ...
- docker_usb开发软件部署
1.docker镜像包 (备注:61提供,带桌面版本) rayosx2.0.2.tar 2.paho-mqtt dnf install git -y git clone https://github ...
- 表格中的IE BUG
在表格应用了跨列单元格后,在IE6/7下当跨列单元格中的元素长度超过其跨列单元格中第一个单元格的宽度时会产生换行,如下所示: 解决方法: 1. 设置 table 的 'table-layout' 特性 ...
- ACboy needs your help-分组背包模板题
id=17676" target="_blank" style="color:blue; text-decoration:none">ACboy ...
- mysql 5.7 安装手册(for linux)
1.下载和解压mysql数据库 wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.9-linux-glibc2.5-x86_6 ...
- C# 0-1背包问题
0-1背包问题 0-1背包问题基本思想: p[i,j]表示在前面i个物品总价值为j时的价值最大值.str[i, j]表示在前面i个物品总价值为j时的价值最大值时的物品重量串. i=0 或者j=0时: ...