Spring Boot @Scheduled定时任务代码实例解析定时任务代码实例解析
主要介绍了Spring Boot @Scheduled定时任务代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习
或者工作具有一定的参考学习价值,需要的朋友可以参考下
假设我们已经搭建好了一个基于Spring Boot项目,首先我们要在Application中设置启用定时任务功能@EnableScheduling。
启动定时任务启动定时任务
package com.scheduling;
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 注解的作用是发现注解@Scheduled的任务并后台执行。
定时任务具体实现类定时任务具体实现类
接下来我们来创建一个定时任务
package com.Scheduler.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Scheduler{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//每隔2秒执行一次
@Scheduled(fixedRate = 2000)
public void testTasks() {
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}
//每天3:05执行
@Scheduled(cron = "0 05 03 ? * *")
public void testTasks() {
System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}
}
运行Spring Boot,输出结果为如下,每2秒钟打印出当前时间。
定时任务执行时间:23:28:00
定时任务执行时间:23:28:02
定时任务执行时间:23:28:04
定时任务执行时间:23:28:06
定时任务执行时间:23:28:08
注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任
务。
关注微信公众号:Java技术栈,在后台回复:boot,可以获取我整理的 N 篇最新Spring Boot 教程,都是干货。
@Scheduled参数描述参数描述
@Scheduled(fixedRate=3000):上一次_开始执行时间_点后3秒再次执行;
@Scheduled(fixedDelay=3000):上一次_执行完毕时间_点3秒再次执行;
@Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次_执行完毕时间_点3秒再次执行;