简介
- jdk之Timer
- jdk之ScheduledThreadPoolExecutor
- spring之TaskScheduler
- quartz
一. jdk之Timer
- schedule(TimerTask task, long delay) 延迟 delay 毫秒 执行
- schedule(TimerTask task, Date time) 特定时间执行
- schedule(TimerTask task, long delay, long period) 延迟 delay 毫秒 执行并每隔period 毫秒 执行一次
// 延迟2秒, 每隔3秒打印一次当前时间
public static void main(String[] args) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println(LocalDateTime.now());
}
}, 2000L, 3000L);
}
二. jdk之ScheduledThreadPoolExecutor
ScheduledExecutorService 接口实现类
ScheduledExecutorService 是JAVA 1.5 后新增的定时任务接口,主要有以下几个方法。
1. ScheduledFuture<?> schedule(Runnable command,long delay, TimeUnit unit);
2. <V> ScheduledFuture<V> schedule(Callable<V> callable,long delay, TimeUnit unit);
3. ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnitunit);
4. ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnitunit);
// 延迟2秒, 每隔2秒钟打印一次当前时间
public static void main(String[] args) {
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
scheduledThreadPoolExecutor.scheduleAtFixedRate(()->System.out.println(LocalDateTime.now()), 2L, 2L, TimeUnit.SECONDS);
}
三. spring之TaskScheduler
介绍: 轻量级quartz, 使用起来简单
使用方式:
- 配置式
<task:scheduler id="myScheduler" pool-size="10" />
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="job" method="test" cron="0 * * * * ?"/>
</task:scheduled-tasks>
- 注解式(最常用)
- 先启用注解
spring项目需要再配置文件中启用
<task:scheduler id="myScheduler" pool-size="10" />
// 启用注解
<task:annotation-driven scheduler="myScheduler"/>
springboot项目需要在启动类中启用注解
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
// 启用注解
@EnableScheduling
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
- 再使用注解和cron表达式
// 每隔5秒钟执行一次test方法
@Scheduled(cron = "0/5 * * * * ?")
public void test() {
System.out.println(LocalDateTime.now());
}
- 编程式(略…)