Spring-计划任务

目标

创建一个每 5s 打印一次当前时间的应用程序。

Spring initializr 配置

https://start.spring.io
无需额外添加依赖。

添加依赖库

添加 awaitility 依赖库,使用 maven 管理依赖

1
2
3
4
5
6
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>

注: awaitility 库的较新版本不适应本例程,所以手动指定版本。

新建 ScheduledTasks 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.schedulingtasks;

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

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

@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()));
}
}

fixedRate 指定了方法两次调用之间的间隔时间(本次的调用开始时间-上次的调用开始时间),此外还有选项如 fixedDelay 指定的是两次方法调用结束时间的间隔。

开启 Scheduling

ScheduledTasks 可以内嵌在别的网络应用程序中,但这里为了演示方便,我们简单打包成一个单独的程序。

所以需要 SchedulingTasksApplication 的 main 方法来调用,只需要额外添加 @EnableScheduling 注解即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.example.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

public static void main(String[] args) {
SpringApplication.run(SchedulingTasksApplication.class, args);
}

}

运行后,可以直接在命令行看到:

1
2
3
4
2022-12-01 21:46:27.305  INFO 58412 --- [   scheduling-1] c.e.schedulingtasks.ScheduledTasks       : The time is now 21:46:27
2022-12-01 21:46:32.304 INFO 58412 --- [ scheduling-1] c.e.schedulingtasks.ScheduledTasks : The time is now 21:46:32
2022-12-01 21:46:37.309 INFO 58412 --- [ scheduling-1] c.e.schedulingtasks.ScheduledTasks : The time is now 21:46:37
2022-12-01 21:46:42.306 INFO 58412 --- [ scheduling-1] c.e.schedulingtasks.ScheduledTasks : The time is now 21:46:42
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022 qusong
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信