美文网首页
Spring Boot Scheduled 的使用

Spring Boot Scheduled 的使用

作者: Xiong忄s | 来源:发表于2017-11-23 13:30 被阅读134次

在开发中很多地方需要用到定时任务,如定时发送邮件,清理数据等,在Spring Boot 中已经帮我们实现了,只需要增加相应的注解即可。

  1. pom配置
  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 启动类增加@EnableScheduling注解,即可开启定时
@EnableScheduling
@SpringBootApplication
public class XiongxsScheduledApplication {

    public static void main(String[] args) {
        SpringApplication.run(XiongxsScheduledApplication.class, args);
    }
}
  1. 编写定时任务实现类
//任务1
@Component
public class ScheduledTask {

    private int count = 0;

    @Scheduled(cron = "*/6 * * * * ?")
    private void proess() {
        System.out.println("count = " + count++);
    }
}
//任务2
@Component
public class Scheduled2Task {

    private static final SimpleDateFormat dataFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    private void reportCurrentTime() {
        System.out.println("现在时间" + dataFormat.format(new Date()));
    }

}

运行结果

count = 0
现在时间13:23:10
count = 1
现在时间13:23:16
count = 2
现在时间13:23:22
count = 3
现在时间13:23:28
count = 4
现在时间13:23:34
count = 5
现在时间13:23:40
  1. 注解参数说明
@Component   泛指组建,当组建不好归类的时候用这个注解标注,把普通的POJO类实例化到Spring的IOC容器中。
@EnableScheduling 开启定时
@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate 说明
@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次

相关文章

网友评论

      本文标题:Spring Boot Scheduled 的使用

      本文链接:https://www.haomeiwen.com/subject/yilzvxtx.html