如果不知道如何使用 Spring,请先查看 Building a RESTful Web Service。
官方文章地址:https://spring.io/guides/gs/scheduling-tasks/
下载地址
git clone https://github.com/spring-guides/gs-scheduling-tasks.git
实现示例:使用 @Scheduled
每 5 秒输出当前时间。
build.gradle 文件:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-scheduling-tasks'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter")
testCompile("junit:junit")
}
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()));
}
}
Scheduled
用于方法启动一个任务,fixedRate
指定任务的频率,这里是5000毫秒。其他选项查看 other options,使用 @Scheduled(cron=". . .")
指定更加复杂的任务,详情查看 这里。
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);
}
}
@EnableScheduling
开启后台任务,否则不会启动 Scheduling。
输出信息如下:
2017-06-11 11:50:01.092 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:01
2017-06-11 11:50:06.094 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:06
2017-06-11 11:50:11.091 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:11
2017-06-11 11:50:16.095 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:16
2017-06-11 11:50:21.094 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:21
2017-06-11 11:50:26.091 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:26
2017-06-11 11:50:31.094 INFO 4351 --- [pool-1-thread-1] hello.ScheduledTasks : The time is now 11:50:31
网友评论