# 定时任务
在Spring Boot中添加定时任务可以使用@Scheduled
注解。以下是一个简单的例子:
首先,确保在Spring Boot应用程序的主类(带有@SpringBootApplication
注解的类)或者配置类上添加@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);
}
}
然后,在你的定时任务类中创建一个方法,并使用@Scheduled
注解来标记该方法作为定时任务。以下是一个例子:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000) // 每5秒执行一次
public void doSomething() {
// 执行定时任务的逻辑
System.out.println("定时任务执行中...");
}
}