Spring Boot如何使用@Scheduled创建定时任务呢?
在日常工作中,我们经常需要定义发送一些邮件 、定时处理一些单据状态 那么这些需求,在Springboot中该如何实现呢?下文笔者讲述springboot创建定义任务的方法分享,如下所示
实现思路:
1.启动类上加入@EnableScheduling注解
2.使用@Scheduled注解定义组件的运行时间点
例:springboot创建一个定时任务
在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
创建定时任务实现类
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("我是一个定时任务" + dateFormat.format(new Date()));
}
}
运行SpringBoot程序,定时任务程序,则会运行
@Scheduled注解其他说明
@Scheduled(fixedRate = 5000):
上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000):
上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000):
第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron="*/5 * * * * *"):
通过cron表达式定义规则
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


