Spring Boot 之 Scheduling Tasks定时任务

<span style="color:#ffffff;">
</span>

几乎大部分的应用都会有定时执行任务的需求。使用Spring Boot 之Scheduling Tasks 能够提高您的开发效率。

下载demo :  git clone  https://github.com/spring-guides/gs-scheduling-tasks.git  ;

使用IDEA 或者eclipse 打开项目

进入   cd into gs-scheduling-tasks/initial 这个项目

src/main/java/hello/ScheduledTasks.java

package hello;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

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

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}
@Componet 注解 能使Spring 找到该类。

@Scheduled  注解 定义一个特定的方法,fixedRate,表示任务开始执行时间间隔,单位毫米。f ixedDelay 表示 任务延迟执行,并

按照该时间间隔执行。也可以用更复杂些的定时配置 @Scheduled(cron=". . .") expressions for more sophisticated task scheduling.


启用定时功能

创建类

src/main/java/hello/Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {

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

@SpringBootApplication SpringBoot 项目的基础配置,详情请看上一章

@EnableScheduling 确保在后台创建一个任务执行者。

运行 main 方法 

你将会看到 每5秒执行一次 

[...]
2016-08-25 13:10:00.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:00
2016-08-25 13:10:05.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:05
2016-08-25 13:10:10.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:10
2016-08-25 13:10:15.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:15
原文: https://spring.io/guides/gs/scheduling-tasks/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值