在实际开发过程中,经常遇到需要用到定时任务的场景,一种是在固定的时间点执行某个任务,比如每天0点执行任务;另一种是延迟执行任务,比如在某方法运行后过20分钟以后执行任务,可以用在临时数据的删除等场景。这里简单介绍两种场景下的定时任务实现方法。
一. 定时执行
1. 在你的Spring Boot应用程序的主类上添加@EnableScheduling
注解,以启用定时任务的支持
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
2. 创建一个带有定时任务方法的类,并在该方法上添加@Scheduled
注解来指定任务的执行时间。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduledTasks {
@Scheduled(fixedRate = 5000) // 每隔5秒执行一次任务
public void myTask1() {
// 执行你的定时任务逻辑
System.out.println("定时任务执行中...");
}
@Scheduled(cron = "0 0 0 * * ?") // 每天0点执行任务
public void myTask2() {
// 执行你的定时任务逻辑
System.out.println("定时任务执行中...");
}
使用@Scheduled
注解的cron
属性来指定Cron表达式,Cron表达式的语法如下:
秒 分 时 日 月 周 年(可选)
其中,*
表示任意值,?
表示不指定,0 0 0 * * ?
表示每天的0点。
二. 延时执行
1. 创建一个TimeTask
实例继承Runnable接口,重写run方法。
import javax.annotation.Resource;
public class TimeTask implements Runnable{
@Resource
private TaskExample taskExample;
private String message;
public TimeTask(String message) {
this.message = message;
}
@Override
public void run() {
taskExample.sayHello();
System.out.println(message);
}
}
TaskExample 类即为需要定时执行的目标方法所在的类:
import org.springframework.stereotype.Service;
@Service
public class TaskExample {
public void sayHello() {
System.out.println("Hello!");
}
}
2. 在服务类中注入TaskScheduler
,实现定时任务。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import java.time.Instant;
@Service
public class TimeTaskService {
@Autowired
private TaskScheduler taskScheduler;
public void test() {
System.out.println("start");
TimeTask timeTask = new TimeTask("end");
taskScheduler.schedule(timeTask, Instant.now().plusSeconds(20)); //20秒后执行任务
}
}
需要延迟多久根据需求自己设定 Instant.now() 的值就行了