在Spring Boot中,@Scheduled
注解可以用来创建定时任务。以下是一个简单的例子,展示了如何使用@Scheduled
注解来创建一个每5秒执行一次的定时任务。
一、配置定时任务
首先,在Spring Boot主类或配置类中启用定时任务支持@EnableScheduling:
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableScheduling
public class ScheduledTaskApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledTaskApplication.class);
}
}
二、定时任务类
然后,创建一个定时任务的类,并使用@Scheduled
注解来标注你想要定时执行的方法:
package com.lenovo.datacollector.consumer.component;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class ScheduledTasks {
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
// 每隔固定时间执行,单位毫秒
@Scheduled(fixedRate = 5000) // 每隔5秒执行一次
public void fixedRateTask() {
System.out.println("Fixed rate task - " + LocalDateTime.now().toString());
}
// 固定延迟时间执行,单位毫秒
@Scheduled(fixedDelay = 10000) // 上次执行完毕时间点后10秒再执行
public void fixedDelayTask() {
System.out.println("Fixed delay task - " + LocalDateTime.now().toString());
}
// 使用Cron表达式执行,每天凌晨1点执行
@Scheduled(cron = "0 0 1 * * ?")
public void cronTask() {
System.out.println("Cron task - " + LocalDateTime.now().toString());
}
}
三、cron表达式
在日常开发中,可以借助下面的网站快速生成cron表达式,配置实例:
- 每隔5秒执行一次:/5 * ?
- 每隔1分钟执行一次:0 /1 ?
- 0 0 10,14,16 ? 每天上午10点,下午2点,4点
- 0 0/30 9-17 ? 朝九晚五工作时间内每半小时
- 0 0 12 ? * WED 表示每个星期三中午12点
- “0 0 12 ?” 每天中午12点触发
- “0 15 10 ? “ 每天上午10:15触发
- “0 15 10 ?” 每天上午10:15触发
- “0 15 10 ? *” 每天上午10:15触发
- “0 15 10 ? 2005” 2005年的每天上午10:15触发
- “0 14 * ?” 在每天下午2点到下午2:59期间的每1分钟触发
- “0 0/5 14 ?” 在每天下午2点到下午2:55期间的每5分钟触发
- “0 0/5 14,18 ?” 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
- “0 0-5 14 ?” 在每天下午2点到下午2:05期间的每1分钟触发
- “0 10,44 14 ? 3 WED” 每年三月的星期三的下午2:10和2:44触发
- “0 15 10 ? * MON-FRI” 周一至周五的上午10:15触发
- “0 15 10 15 * ?” 每月15日上午10:15触发
- “0 15 10 L * ?” 每月最后一日的上午10:15触发
- “0 15 10 ? * 6L” 每月的最后一个星期五上午10:15触发
- “0 15 10 ? * 6L 2002-2005” 2002年至2005年的每月的最后一个星期五上午10:15触发
- “0 15 10 ? * 6#3” 每月的第三个星期五上午10:15触发