概述

要使用@ Scheduled注解,首先需要在启动类添加@ EnableScheduling,启用Spring的计划任务执行功能,这样可以在容器中的任何Spring管理的bean上检测@ Scheduled注解,执行计划任务。

注解定义

/**
* An annotation that marks a method to be scheduled. Exactly one of
* the {@link #cron()}, {@link #fixedDelay()}, or {@link #fixedRate()}
* attributes must be specified.
*
* <p>The annotated method must expect no arguments. It will typically have
* a {@code void} return type; if not, the returned value will be ignored
* when called through the scheduler.
*
* <p>Processing of {@code @Scheduled} annotations is performed by
* registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
* done manually or, more conveniently, through the {@code <task:annotation-driven/>}
* element or @{@link EnableScheduling} annotation.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em> with attribute overrides.
*
* @author Mark Fisher
* @author Dave Syer
* @author Chris Beams
* @since 3.0
* @see EnableScheduling
* @see ScheduledAnnotationBeanPostProcessor
* @see Schedules
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled { /**
* A cron-like expression, extending the usual UN*X definition to include
* triggers on the second as well as minute, hour, day of month, month
* and day of week. e.g. {@code "0 * * * * MON-FRI"} means once per minute on
* weekdays (at the top of the minute - the 0th second).
* @return an expression that can be parsed to a cron schedule
* @see org.springframework.scheduling.support.CronSequenceGenerator
*/
String cron() default ""; /**
* A time zone for which the cron expression will be resolved. By default, this
* attribute is the empty String (i.e. the server's local time zone will be used).
* @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
* or an empty String to indicate the server's default time zone
* @since 4.0
* @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
* @see java.util.TimeZone
*/
String zone() default ""; /**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds
*/
long fixedDelay() default -1; /**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds as a String value, e.g. a placeholder
* @since 3.2.2
*/
String fixedDelayString() default ""; /**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds
*/
long fixedRate() default -1; /**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds as a String value, e.g. a placeholder
* @since 3.2.2
*/
String fixedRateString() default ""; /**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds
* @since 3.2
*/
long initialDelay() default -1;
String initialDelayString() default ""; }

参数说明

参数 参数说明 示例
cron 任务执行的cron表达式 @ Scheduled(cron="0/1 * * * * ?")
zone cron表达时解析使用的时区,默认为服务器的本地时区,使用java.util.TimeZone#getTimeZone(String)方法解析 @ Scheduled(zone =" GMT-8:00")
fixedDelay 上一次任务执行结束到下一次执行开始的间隔时间,单位为ms @ Scheduled(fixedDelay = 1000 * 60)
fixedDelayString 上一次任务执行结束到下一次执行开始的间隔时间,使用java.time.Duration#parse解析 @ Scheduled(fixedDelayString = "PT15M")
fixedRate 以固定间隔执行任务,即上一次任务执行开始到下一次执行开始的间隔时间,单位为ms,
若在调度任务执行时,上一次任务还未执行完毕,会加入worker队列,等待上一次执行完成后立即执行下一次任务
@ Scheduled(fixedRate = 2000)
fixedRateString 与fixedRate逻辑一致,只是使用java.time.Duration#parse解析 @ Scheduled( fixedRateString="PT15M")
initialDelay 首次任务执行的延迟时间 @ Scheduled(initialDelay = 1000)
initialDelayString 首次任务执行的延迟时间,使用java.time.Duration#parse解析 @ Scheduled(initialDelayString = "PT15M")

cron表达式语法

[秒] [分] [小时] [日] [月] [周] [年]

注:[年]不是必须的域,可以省略[年],则一共6个域

使用说明

定时任务执行默认是单线程模式,会创建一个本地线程池,线程池大小为1。当项目中有多个定时任务时,任务之间会相互等待,同步执行

源码

// org.springframework.scheduling.config.ScheduledTaskRegistrar#scheduleTasks
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
} // java.util.concurrent.Executors#newSingleThreadScheduledExecutor()
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}

注意:如果是多节点部署服务器,并且一个定时任务只需要执行一次的情况下,有两种方法实现

  1. 分布式锁
  2. 指定某一节点执行(此种情况会使多节点部署失去意义)

如果想了解分布式锁,请关注我,下期会说分布式锁。

本文作者:好名字

原文链接:定时任务注解@Scheduled

版权声明: 本博客所有文章除特别声明外,均采用 CC BY 3.0 CN协议进行许可。转载请署名作者且注明文章出处。

定时任务注解@Scheduled的更多相关文章

  1. 【Spring】Spring的定时任务注解@Scheduled原来如此简单

    1 简介 定时任务的实现非常多,JDK的Timer.Spring提供的轻量级的Scheduled Task.QuartZ和Linux Cron等,还有一些分布式的任务调度框架.本文主要介绍Schedu ...

  2. spring定时任务注解@Scheduled的记录

    spring 定时任务@Scheduled 转自https://www.cnblogs.com/0201zcr/p/5995779.html 1.配置文件 <?xml version=" ...

  3. spring注解scheduled实现定时任务

    只想说,spring注解scheduled实现定时任务使用真的非常简单. 一.配置spring.xml文件 1.在beans加入xmlns:task="http://www.springfr ...

  4. Spring中使用注解 @Scheduled 执行定时任务

    来自:http://blog.51cto.com/dwf07223/1557145 注解@Scheduled 可以作为一个触发源添加到一个方法中,例如,以下的方法将以一个固定延迟时间5秒钟调用一次执行 ...

  5. Spring中使用注解 @Scheduled执行定时任务

    注解@Scheduled 使用方式 注解@Scheduled 可以作为一个触发源添加到一个方法中,例如,以下的方法将以一个固定延迟时间5秒钟调用一次执行,这个周期是以上一个调用任务的完成时间为基准,在 ...

  6. Spring 定时任务 注解版

    Task类: ManageSql.Java对应代码: package com.axb.cheney.task; import java.sql.ResultSet; import java.sql.S ...

  7. Spring MVC 定时任务注解说明

    一.注解说明. Spring 自带的定时任务执行@Scheduled注解,可以定时的.周期性的执行一些任务.查看@Scheduled的注解可以看到有以下三种: 1.1 String cron() de ...

  8. Spring注解@Scheduled定时任务

    一.首先配置applicationContext-task.xml (1)添加 xmlns:task="http://www.springframework.org/schema/task& ...

  9. java 定时任务之一 @Scheduled注解(第一种方法)

    使用spring @Scheduled注解执行定时任务: 运行!!! 关于Cron表达式(转载) 表达式网站生成: http://cron.qqe2.com/  直接点击 作者:http://blog ...

随机推荐

  1. [对对子队]会议记录5.25(Scrum Meeting11)

    今天已完成的工作 吴桐雨 ​ 工作内容:设计第10.11关 ​ 相关issue:设计额外关卡 ​ 相关签入:level10 level11 吴昭邦 ​ 工作内容:写测试代码 ​ 相关issue:测试初 ...

  2. Beta阶段第九次会议

    Beta阶段第九次会议 时间:2020.5.25 完成工作 姓名 完成工作 任务难度 完成度 ltx 1.发现小程序身份认证bug和新闻列表获取bug2.修改新增页面风格 轻 90% xyq 1.修改 ...

  3. [对对子队]团队任务拆解Alpha

    Alpha阶段主要目标 完成游戏场景的基本实现(不要求美术资源) 完成游戏UI的基本实现(不要求美术资源) 制作第一部分的关卡(顺序语句,制作3-5关) 完成第一部分关卡和游戏基本逻辑的测试 任务分解 ...

  4. 使用logstash的input file filter收集日志文件

    使用logstash的input file filter收集日志文件 一.需求 二.实现步骤 1.前置知识 2.编写pipeline文件 3.Input 中 file 插件的部分参数解释: 4.启动l ...

  5. 扩展spring data jpa的repository

    在我们编写代码的过程中,spring data jpa为我们的持久层提供的极大的方便,但有时spring data jpa提供的repository并不能完全满足我们开发的需求,因此就需要进行扩展.s ...

  6. Noip模拟52 2021.9.13

    T1 异或 比较稳的切掉 观察数据范围,无法线性筛啥的,根号复杂度也会死,于是只能考虑$log$级 然后打表 发现当$n$为$2^i$时的答案是一个可递归数列: $1,3,7,15,31,63,127 ...

  7. stm32学习笔记之串口通信

    在基础实验成功的基础上,对串口的调试方法进行实践.硬件代码顺利完成之后,对日后调试需要用到的printf重定义进行调试,固定在自己的库函数中. b) 初始化函数定义: void USART_Confi ...

  8. objdump--反汇编查看

    转载:objdump命令_Linux objdump 命令用法详解:显示二进制文件信息 (linuxde.net) objdump命令 编程开发 objdump命令是用查看目标文件或者可执行的目标文件 ...

  9. JMH 使用指南

    简介 JMH(Java Microbenchmark Harness)是用于代码微基准测试的工具套件,主要是基于方法层面的基准测试,精度可以达到纳秒级.该工具是由 Oracle 内部实现 JIT 的大 ...

  10. 单自由度系统中质量、阻尼和刚度变化对频率响应函数(FRF)影响图的绘制

    作者:赵兵 日期:2020-02-17 目录 单自由度系统中质量.阻尼和刚度变化对频率响应函数(FRF)影响图的绘制 1.     背景 2.     VISIO绘制 3.     Matlab绘制 ...