Timer
这个是java自带的java.util.Timer类,这个类允许调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定的时间允许,一般用的比较少。
public static void main(String[] args) { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { System.out.println("Task run"+ new Date()); } }; //间隔3s执行一次 timer.schedule(timerTask,10,3000); }
ScheduledExecutorService
这个也是jdk自带的一个类;是基于线程池设定的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互相不会影响。
public static void main(String[] args) { ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); //间隔三秒执行 scheduledExecutorService.scheduleAtFixedRate(()-> System.out.println("Task run"+new Date()),0,3, TimeUnit.SECONDS); }
Spring Task
Spring3.0以后自带的task,可以将其看成是一个轻量级的Quartz,而且使用起来比Quartz简单许多。
//导入相应的依赖,同时需要在主类上注解启动器@EnableScheduling
@Slf4j @Component public class ScheduledService { @Scheduled(cron = "0/5 * * * * *") public void scheduled(){ log.info("=====>>>>>使用cron {}",System.currentTimeMillis()); } @Scheduled(fixedRate = 5000) public void scheduled1() { log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis()); } @Scheduled(fixedDelay = 5000) public void scheduled2() { log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis()); } }
Quartz
这是一个功能比较强大的调度器,可以让你的程序在指定时间内执行,也可以按照某一个频度执行,配置起来稍微复杂。