Spring Scheduler是Spring框架提供的一个简单的定时任务实现。我们使用的时候非常简单,只需要添加几个注解就行。
主要是org.springframework.scheduling.annotation
包下的类。我们先看一下怎么用,然后再分析一下其源码。
代码示例
可以是xml配置,也可以用注解实现。此处选择注解实现。
@Service @Slf4j @Data public class SpringScheduleTest { private AtomicInteger taskNumber = new AtomicInteger(0); private AtomicInteger task1Number = new AtomicInteger(0); @Scheduled(cron = "*/5 * * * * ? ") public void remindTask() throws InterruptedException { log.info("每隔5秒执行一次, 当前线程名称{} 当前执行次数{}", Thread.currentThread().getName(), taskNumber.incrementAndGet()); } /** * 固定频率执行。fixedDelay的单位是ms */ @Scheduled(fixedDelay = 1000) public void remindTask2() throws InterruptedException { log.info("每隔1s执行一次 当前线程名称{} 当前执行次数{}", Thread.currentThread().getName(), task1Number.incrementAndGet()); } } // !!!在启动类上面加上这个注解!!! @SpringBootApplication @EnableScheduling public class QuartzApplication { public static void main(String[] args) { SpringApplication.run(QuartzApplication.class, args); } } // 配置线程池 @Configuration public class ThreadPoolConfig { @Bean public ScheduledExecutorFactoryBean scheduledExecutorFactoryBean() { ScheduledExecutorFactoryBean factoryBean = new ScheduledExecutorFactoryBean(); factoryBean.setPoolSize(20); factoryBean.setThreadNamePrefix("i'm time task thread - "); return factoryBean; } }
优点
- 使用简单。
- 支持cron表达式,支持固定频率执行。
- 代码侵入性低。
缺点
- 无法解决分布式调度问题。
- 无法监控任务状态。
- 无其他骚功能。如失败提醒,重试等等。