SpringTask 使用
一、普通使用
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-task-core</artifactId>
</dependency>
2.在启动类上加上 @EnableScheduling
@SpringBootApplication
@EnableCaching
@EnableScheduling
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}
3.代码例子
在线Cron表达式生成器: http://cron.qqe2.com/
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* cron:使用Cron表达式。每1秒执行一次
*/
@Scheduled(cron = "0/1 * * * * ?")
public void taskWithCorn1() {
log.info("[ScheduledTasks-taskWithCorn1] Current Thread : {}, time:{}", Thread.currentThread().getName(),dateFormat.format(new Date()));
}
/**
* fixedRate:固定速率执行。每1秒执行一次。
*/
@Scheduled(fixedRate = 1000)
public void taskWithFixedRate() {
log.info("[ScheduledTasks-taskWithFixedRate] Current Thread : {}, time:{}", Thread.currentThread().getName(),dateFormat.format(new Date()));
}
/**
* fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
*/
@Scheduled(fixedDelay = 2000)
public void taskWithFixedDelay() {
try {
TimeUnit.SECONDS.sleep(3);
log.info("[ScheduledTasks-taskWithFixedDelay] Current Thread : {}, time:{}", Thread.currentThread().getName(),dateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* initialDelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
*/
@Scheduled(initialDelay = 5000, fixedRate = 5000)
public void taskWithInitialDelay() {
log.info("[ScheduledTasks-taskWithInitialDelay] Current Thread : {}, time:{}", Thread.currentThread().getName(),dateFormat.format(new Date()));
}
}
二、高阶使用
2.1 自定义任务线程池大小
默认情况下,@Scheduled任务都在Spring创建的大小为1的默认线程池中执行。
可运行以上代码查看运行结果
Current Thread : scheduling-1, time:2023-02-07 20:58:32
需要时,可自定义任务线程池的大小
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
private final int SCHEDULER_POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(SCHEDULER_POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("my-scheduled-task-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
2.2 任务并行执行-@EnableAsync,@Async
@EnableAsync 和 @Async 使定时任务并行执行
如果你想要你的代码并行执行的话,还可以通过@EnableAsync 和 @Async这两个注解实现
@Component
@EnableAsync
public class AsyncScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
*/
//@Async
@Scheduled(fixedDelay = 2000)
public void reportCurrentTimeWithFixedDelay() {
try {
TimeUnit.SECONDS.sleep(3);
log.info("Fixed Delay Task : The time is now {}", dateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Spring Task 底层是基于 JDK 的 ScheduledThreadPoolExecutor 线程池来实现的。
优缺点总结:
优点: 简单,轻量,支持 Cron 表达式
缺点 :功能单一