spring boot 学习(八)定时任务 @Scheduled

SpringBoot 定时任务 @Scheduled

前言

有时候,我们有这样的需求,需要在每天的某个固定时间或者每隔一段时间让应用去执行某一个任务。一般情况下,可以使用多线程来实现这个功能;在 Spring 框架下可以搭配 Quartz 来实现,附上笔记 Spring Quartz 实现多任务定时调用。在 SpringBoot 框架下,我们可以用 Spring scheduling 来实现定时任务功能。
首先,我们先创建一个 Spring Boot 项目。创建方法:
* (自动完成初始化)http://blog.csdn.net/u011244202/article/details/54767036
* (手动完成初始化)http://blog.csdn.net/u011244202/article/details/54604421

同时要注意,SpringBoot 项目需要 JDK8 的编译环境!

然后,在项目主类中加入@EnableScheduling注解,启用定时任务的配置

@SpringBootApplication
@EnableScheduling
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

最后,创建定时任务实现类,注意加上注解@Scheduled

@Scheduled 的介绍

1. cron 表达式与 zone

zone:表示将解析cron表达式的时区。
关于 cron 表达式,可以参考一下 http://blog.csdn.net/u011244202/article/details/54382466 里面的附录。

2. fixedRate 的解释

调用固定周期(以毫秒为单位)执行方法。就是上一次开始执行时间点之后延迟执行。

3. fixedDelay 的解释

上次调用结束和下一次调用结束之间的固定周期(以毫秒为单位)执行方法。就是上一次执行完毕时间点之后延迟执行。

4. initialDelay 的解释

在第一次执行fixedRate()或fixedDelay()任务之前延迟(以毫秒为单位)。

实例

在项目启动 8s 后,每隔 5s 调用定时任务。

@Component
public class ScheduledTasks {

    //输出时间格式
    private static final SimpleDateFormat format = new SimpleDateFormat("HH(hh):mm:ss S");

    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void firstScheduledTasks(){
        System.out.println("定时任务执行,现在时间是 : "+format.format(new Date()));
    }
}

 结果图:

这里写图片描述

项目参考地址

项目参考地址 : https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B4

注意:

cron、fixedDelay、fixedRate 三者之间不能共存!!!
会抛出一个错误:

//Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'firstScheduledTasks': Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required.

官方文档

实例文档 : http://spring.io/guides/gs/scheduling-tasks/
注解文档 : http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html

原文地址:https://www.cnblogs.com/MaxElephant/p/8108462.html