scheduling tasks with Spring
这篇文章将完成使用Spring进行任务调度的步骤。
使用IDEA作为开发工具,使用Maven进行项目管理。
Starting with Spring Initialize
首先从Spring Initializr快速创建项目schedulingtasks,配置如下图:
选择GENERATE下载到本地,打开项目后编辑pom.xml文件,添加依赖awaitility。
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>
Create a Scheduled Task
在目录src/main/java/com/example/schedulingtasks/下新建ScheduledTasks.java文件。
package com.example.schedulingtasks;
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()));
}
}
Enable Scheduling
编辑SchedulingTasksApplication.java文件。
package com.example.schedulingtasks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class);
}
}
Test
运行SchedulingTasksApplication.java,可以看到控制台每隔5秒打印一次时间。
Summary
在这里主要对过程中用到的注解进行总结
@Scheduled
这个注解定义了某个特定的方法何时运行。
在本例中,我们使用的是fixedRate,它指定从每次方法被调用的开始时间来计算方法调用之间的间隔。同样,还有fixedDelay选项,它表示从方法完成的时间开始计算调用的间隔。@scheduled(cron="…") 是更复杂的任务调度表达式。
@EnableScheduling
这个注解确保创建了一个后台任务执行器,如果没有此注解,所有任务都不会被安排。