Spring Boot 定时任务实例分析

首先使用maven搭建一个Springboot 项目。
添加依赖到pom.xml中

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

我们都知道,springboot有一个自己的入口,也就是@SpringBootApplication(他是一个组合注解 由@Configuration,@EnableAutoConfiguration和@ComponentScan组成)

定时器需要有一个总开关,因为我可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。

启动类开启定时调度器

-Application.java

@SpringBootApplication
@EnableScheduling   //开启定时器
public class SpringbootHelloApplication {
public static void main(String[] args) {
        SpringApplication.run(SpringbootHelloApplication.class, args);
    }
}

创建定时器

  • SchedulerTaskDemo.java
package com.teracloud.teops.web.utils;

import java.util.Date;

import org.slf4j.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 
* @ClassName: SchedulerTaskDemo  
* @Description: TODO(这里用一句话描述这个类的作用)  
* @author dcr
* @date 2018年3月21日  
*
 */
@Component
public class SchedulerTaskDemo {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Scheduled(cron="*/5 * * * * ?")
    public void dateTask() {
        LOG.info("SchedulerTaskDemo:" + new Date().toString());
    }

}

启动工程之后,每隔5秒打印一段时间。

这里写图片描述

参数说明

@Scheduled 注解

@Scheduled 注解可以接受两种定时的设置,一种是我们常用的cron=”/5 * * * ?” ,一种是 fixedRate=5000,两种都表示每隔五秒打印一下内容。

cron 参数

一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。按顺序依次为

秒(0~59)

分钟(0~59)

小时(0~23)

天(月)(0~31,但是你需要考虑你月的天数)

月(0~11)

天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)

7.年份(1970-2099)

猜你喜欢

转载自blog.csdn.net/dengchenrong/article/details/79641442
今日推荐