文章内容
一、实现方式
- 1、Java自带的java.util.Timer类,允许调度一个java.util.TimerTask任务。最早的时候就是这样写定时任务的
- 2、开源的第三方框架: Quartz 或者 elastic-job。比较复杂和重量级,适用于分布式场景下的定时任务,可以根据需要多实例部署定时任务
- 3、使用Spring提供的注解: @Schedule。定时任务执行时间较短,并且比较单一,可以使用这个注解
1、 启动定时任务@EnableScheduling
1 2 3 4 5 6 7 | @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application. class , args); } } |
2、串行方式(单线程)
使用的注解: @Scheduled
01 02 03 04 05 06 07 08 09 10 | @Component public class ScheduledController { @Scheduled (cron = "0 0/2 * * * ?" ) public void pushScheduled(){ log.info( "start push scheduled!" ); // TODO log.info( "end push scheduled!" ); } } |
3、并行方式(多线程)
当定时任务很多的时候,为了提高任务执行效率,可以采用并行方式执行定时任务,任务之间互不影响, 只要实现SchedulingConfigurer接口就可以
01 02 03 04 05 06 07 08 09 10 11 | @Configuration public class ScheduledConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(setTaskExecutors()); } @Bean (destroyMethod= "shutdown" ) public Executor setTaskExecutors(){ return Executors.newScheduledThreadPool( 3 ); // 3个线程来处理。 }} |
二、cron表达式( 秒、分、时、日、月、年)
1 2 3 | 0 0 10,14,16 * * ? #每天上午10点,下午2点,4点 0 0 12 * * ? #每天中午12点触发 0 0/5 0 * * ? #每5分钟执行一次 |