1、實現定時任務的實現方式
- Timer:這是java自帶的java.util.Timer類,這個類允許你調度一個java.util.TimerTask任務。使用這種方式可以讓你的程序按照某一個頻度執行,但不能在指定時間運行。一般用的較少。
- ScheduledExecutorService:也jdk自帶的一個類;是基於線程池設計的定時任務類,每個調度任務都會分配到線程池中的一個線程去執行,也就是說,任務是併發執行,互不影響。
- Spring Task:Spring3.0以後自帶的task,可以將它看成一個輕量級的Quartz,而且使用起來比Quartz簡單許多。
- Quartz:這是一個功能比較強大的的調度器,可以讓你的程序在指定時間執行,也可以按照某一個頻度執行,配置起來稍顯複雜。
1.1 Timer實現方式
package com.demo.test;
import com.demo.util.DateUtils;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class time {
public static void main(String[] args) {
timer();
}
public static void timer(){
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
//System.out.println("task run:"+ new Date());
System.out.println("執行時間爲:"+ DateUtils.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
}
};
Timer timer = new Timer();
//安排指定的任務在指定的時間開始進行重複的固定延遲執行。這裏是每3秒執行一次
timer.schedule(timerTask,10,3000);
}
}
1.2 ScheduledExecutorService
package com.demo.test;
import com.demo.util.DateUtils;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class time {
public static void main(String[] args) {
timer();
ScheduledExecutorService();
}
public static void timer(){
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
//System.out.println("task run:"+ new Date());
System.out.println("執行時間爲:"+ DateUtils.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
}
};
Timer timer = new Timer();
//安排指定的任務在指定的時間開始進行重複的固定延遲執行。這裏是每3秒執行一次
timer.schedule(timerTask,10,3000);
}
public static void ScheduledExecutorService(){
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// 參數:1、任務體 2、首次執行的延時時間 3、任務執行間隔 4、間隔時間單位
service.scheduleAtFixedRate(()->System.out.println("執行時間爲:"+ DateUtils.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss")), 0, 3, TimeUnit.SECONDS);
}
}
1.3 spring task
需要在項目啓動類加上 @EnableScheduling 開啓定時任務
package com.demo.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Test_task {
//@Component 註冊爲spring組件
@Scheduled(cron="0 */1 * * * ?")
public void Test_task(){
System.out.println("定時1分鐘執行一次");
}
}