Spring Boot中的@Scheduled
注解用于配置定时任务,使得方法可以按照规定的时间间隔或特定的时间点定时执行。下面将详细解释@Scheduled注解的使用方法及其实战应用。
@Scheduled
注解可以应用于方法上,并通过不同的参数来指定任务的执行时间、循环周期等。它主要支持以下几种时间配置方式:
cron 表达式在线解析可以参考
https://cron.qqe2.com/
要在Spring Boot项目中启用定时任务,首先需要在启动类上添加@EnableScheduling
注解。这个注解会开启Spring的任务调度功能,使得被@Scheduled
注解的方法能够按照指定的时间规则执行。
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
接下来,可以创建一个定时任务类,并在其中定义被@Scheduled注解的方法。这个类通常会被@Component
注解标记,以便Spring容器能够扫描到它。
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void fixedRateTask() {
System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(fixedDelay = 10000)
public void fixedDelayTask() {
System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
}
@Scheduled(cron = "0 0 1 * * ?")
public void cronTask() {
System.out.println("Cron task - " + System.currentTimeMillis() / 1000);
}
}
Spring支持异步执行定时任务,只需在方法上添加@Async注解,并确保在配置类上添加@EnableAsync注解。
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncScheduleConfig {
// 配置类内容
}
@Component
public class AsyncScheduledTasks {
@Async
@Scheduled(fixedRate = 10000)
public void asyncTask() {
System.out.println("Async Task - 异步执行的定时任务");
}
}
public
。分布式锁
等机制,避免多个节点同时执行同一个任务
。如果@Scheduled任务没有按预期执行,可能是由以下几个原因造成的:
@EnableScheduling
注解,并且Spring容器能够扫描到包含@Scheduled注解的类。在Spring Boot中,@Scheduled注解是基于Java的ThreadPoolExecutor
和ScheduledThreadPoolExecutor
实现的。Spring Boot会创建一个ScheduledThreadPoolExecutor
线程池,并将定时任务添加到该线程池中等待执行。在指定的时间到来后,线程池会为定时任务分配一个线程来执行。
为了避免多线程问题,可以将@Scheduled任务交给线程池进行处理。以下是两种常见的方法:
@Configuration
@EnableScheduling
public class TaskSchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10); // 设置线程池大小
scheduler.initialize();
return scheduler;
}
}
在这个配置中,通过ThreadPoolTaskScheduler创建了一个线程池,并设置了线程池的大小。
@Configuration
@EnableScheduling
public class TaskExecutorConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 设置核心线程池大小
executor.setMaxPoolSize(50); // 设置最大线程池大小
executor.setQueueCapacity(1000); // 设置队列容量
executor.setKeepAliveSeconds(60); // 设置线程存活时间
executor.setThreadNamePrefix("task-executor-"); // 设置线程名称前缀
return executor;
}
}
在这个配置中,通过ThreadPoolTaskExecutor创建了一个线程池,并配置了线程池的核心参数。