Spring Boot 之 Scheduling Tasks定时任务

来源:互联网 发布:微表情心理学软件 编辑:程序博客网 时间:2024/05/16 18:01

<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;@Componentpublic 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@EnableSchedulingpublic 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:002016-08-25 13:10:05.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:052016-08-25 13:10:10.143  INFO 31565 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 13:10:102016-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 0