為什么需要定時(shí)任務(wù)
生活中定時(shí)任務(wù)的需求越來(lái)越多霹俺,場(chǎng)景也越來(lái)越多
如何實(shí)現(xiàn)定時(shí)任務(wù)
- Java自帶的java.util.Timer類(lèi)东揣,這個(gè)類(lèi)允許你調(diào)度一個(gè)java.util.TimerTask任務(wù)匾二。使用這種方式可以讓你的程序按照某一個(gè)頻度執(zhí)行岩饼,但不能在指定時(shí)間運(yùn)行氓辣。一般用的較少诵次,這篇文章將不做詳細(xì)介紹账蓉。
- 使用線程池來(lái)實(shí)現(xiàn)定時(shí)
- Spring3.0以后自帶的task枚碗,可以將它看成一個(gè)輕量級(jí)的Quartz,而且使用起來(lái)比Quartz簡(jiǎn)單許多铸本,稍后會(huì)介紹肮雨。
兩種方法的實(shí)現(xiàn)例子
- timer類(lèi)
public class MyTimer {
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
LocalDateTime current = LocalDateTime.now();
String timeString = current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("task run:"+ timeString);
}
};
Timer timer = new Timer();
//定時(shí)任務(wù)3秒后啟動(dòng),每1秒執(zhí)行一次
timer.schedule(timerTask,3000,1000);
}
}
- 線程池
@Component
public class TimeService {
public final static long ONE_Minute = 60 * 1000;
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
@Scheduled(fixedDelay=ONE_Minute)
public void fixedDelayJob(){
System.out.println(format.format(new Date())+" >>fixedDelay執(zhí)行....");
}
@Scheduled(fixedRate=ONE_Minute)
public void fixedRateJob(){
System.out.println(format.format(new Date())+" >>fixedRate執(zhí)行....");
}
@Scheduled(cron="0 15 3 * * ?")
public void cronJob(){
System.out.println(format.format(new Date())+" >>cron執(zhí)行....");
}
}
public class ScheduledExecutorServiceDemo {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
LocalDateTime current = LocalDateTime.now();
// 參數(shù):1箱玷、任務(wù)體 2怨规、首次執(zhí)行的延時(shí)時(shí)間
// 3、任務(wù)執(zhí)行間隔 4锡足、間隔時(shí)間單位
service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+current.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))), 3, 1, TimeUnit.SECONDS);
}
}
源碼
https://github.com/heiyeziran/JPA/tree/master/schedulertask/src/main/java/com/example/demo/task