java 定時任務實現方式

簡介

  1. jdk之Timer
  2. jdk之ScheduledThreadPoolExecutor
  3. spring之TaskScheduler
  4. quartz

一. jdk之Timer

  1. schedule(TimerTask task, long delay) 延遲 delay 毫秒 執行
  2. schedule(TimerTask task, Date time) 特定時間執行
  3. 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, 使用起來簡單
使用方式:

  1. 配置式
<task:scheduler id="myScheduler" pool-size="10" />
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="job" method="test" cron="0 * * * * ?"/>
</task:scheduled-tasks>
  1. 註解式(最常用)
  • 先啓用註解
    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());
}
  1. 編程式(略…)

四. quartz

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章