Java 定时任务技术
-
定时任务是每个业务常见的需求,比如每分钟扫描超时支付的订单,每小时清理一次数据库历史数据,每天统计前一天的数据并生成报表等等。
使用 Timer
-
创建 java.util.TimerTask 任务,在 run 方法中实现业务逻辑。通过 java.util.Timer 进行调度,支持按照固定频率执行。所有的 TimerTask 是在同一个线程中串行执行,相互影响。也就是说,对于同一个 Timer 里的多个 TimerTask 任务,如果一个 TimerTask 任务在执行中,其它 TimerTask 即使到达执行的时间,也只能排队等待。如果有异常产生,线程将退出,整个定时任务就失败。
-
import java.util.Timer; import java.util.TimerTask; public class TestTimerTask { public static void main(String[] args) { TimerTask timerTask = new TimerTask() { @Override public void run() { System.out.println("hell world"); } }; Timer timer = new Timer(); timer.schedule(timerTask, 10, 3000); } }
使用 ScheduledExecutorService
-
基于线程池设计的定时任务解决方案,每个调度任务都会分配到线程池中的一个线程去执行,解决 Timer 定时器无法并发执行的问题,支持 fixedRate 和 fixedDelay。
-
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TestTimerTask { public static void main(String[] args) { ScheduledExecutorService ses = Executors.newScheduledThreadPool(5); //按照固定频率执行,每隔5秒跑一次 ses.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("hello fixedRate"); } }, 0, 5, TimeUnit.SECONDS); //按照固定延时执行,上次执行完后隔3秒再跑 ses.scheduleWithFixedDelay(new Runnable() { @Override public void run() { System.out.println("hello fixedDelay"); } }, 0, 3, TimeUnit.SECONDS); } }
Spring Task
-
Springboot 中提供了一套轻量级的定时任务工具 Spring Task,通过注解可以很方便的配置,支持 cron 表达式、fixedRate、fixedDelay。
-
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling public class MyTask { /** * 每分钟的第30秒跑一次 */ @Scheduled(cron = "30 * * * * ?") public void task1() throws InterruptedException { System.out.println("hello cron"); } /** * 每隔5秒跑一次 */ @Scheduled(fixedRate = 5000) public void task2() throws InterruptedException { System.out.println("hello fixedRate"); } /** * 上次跑完隔3秒再跑 */ @Scheduled(fixedDelay = 3000) public void task3() throws InterruptedException { System.out.println("hello fixedDelay"); } }
-
Spring Task 相对于上面提到的两种解决方案,最大的优势就是支持 cron 表达式,可以处理按照标准时间固定周期执行的业务,比如每天几点几分执行。