java实现自动任务_Java实现定时任务的三种方法
普通thread
這是最常見(jiàn)的,創(chuàng)建一個(gè)thread,然后讓它在while循環(huán)里一直運(yùn)行著,通過(guò)sleep方法來(lái)達(dá)到定時(shí)任務(wù)的效果。這樣可以快速簡(jiǎn)單的實(shí)現(xiàn),代碼如下:
public?class?Task1?{
public?static?void?main(String[]?args)?{
//?run?in?a?second
final?long?timeInterval?=?1000;
Runnable?runnable?=?new?Runnable()?{
public?void?run()?{
while?(true)?{
//?-------?code?for?task?to?run
System.out.println("Hello?!!");
//?-------?ends?here
try?{
Thread.sleep(timeInterval);
}?catch?(InterruptedException?e)?{
e.printStackTrace();
}
}
}
};
Thread?thread?=?new?Thread(runnable);
thread.start();
}
}
用Timer和TimerTask
上面的實(shí)現(xiàn)是非常快速簡(jiǎn)便的,但它也缺少一些功能。
用Timer和TimerTask的話與上述方法相比有如下好處:
當(dāng)啟動(dòng)和去取消任務(wù)時(shí)可以控制
第一次執(zhí)行任務(wù)時(shí)可以指定你想要的delay時(shí)間
在實(shí)現(xiàn)時(shí),Timer類可以調(diào)度任務(wù),TimerTask則是通過(guò)在run()方法里實(shí)現(xiàn)具體任務(wù)。
Timer實(shí)例可以調(diào)度多任務(wù),它是線程安全的。
當(dāng)Timer的構(gòu)造器被調(diào)用時(shí),它創(chuàng)建了一個(gè)線程,這個(gè)線程可以用來(lái)調(diào)度任務(wù):
import?java.util.Timer;
import?java.util.TimerTask;
public?class?Task2?{
public?static?void?main(String[]?args)?{
TimerTask?task?=?new?TimerTask()?{
@Override
public?void?run()?{
//?task?to?run?goes?here
System.out.println("Hello?!!!");
}
};
Timer?timer?=?new?Timer();
long?delay?=?0;
long?intevalPeriod?=?1?*?1000;
//?schedules?the?task?to?be?run?in?an?interval
timer.scheduleAtFixedRate(task,?delay,
intevalPeriod);
}?//?end?of?main
}
ScheduledExecutorService
ScheduledExecutorService是從Java SE 5的java.util.concurrent里,做為并發(fā)工具類被引進(jìn)的,這是最理想的定時(shí)任務(wù)實(shí)現(xiàn)方式。
相比于上兩個(gè)方法,它有以下好處:
相比于Timer的單線程,它是通過(guò)線程池的方式來(lái)執(zhí)行任務(wù)的
可以很靈活的去設(shè)定第一次執(zhí)行任務(wù)delay時(shí)間
提供了良好的約定,以便設(shè)定執(zhí)行的時(shí)間間隔
我們通過(guò)ScheduledExecutorService#scheduleAtFixedRate展示這個(gè)例子,通過(guò)代碼里參數(shù)的控制,首次執(zhí)行加了delay時(shí)間:
import?java.util.concurrent.Executors;
import?java.util.concurrent.ScheduledExecutorService;
import?java.util.concurrent.TimeUnit;
public?class?Task3?{
public?static?void?main(String[]?args)?{
Runnable?runnable?=?new?Runnable()?{
public?void?run()?{
//?task?to?run?goes?here
System.out.println("Hello?!!");
}
};
ScheduledExecutorService?service?=?Executors
.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable,?0,?1,?TimeUnit.SECONDS);
}
}
總結(jié)
以上是生活随笔為你收集整理的java实现自动任务_Java实现定时任务的三种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 5G~ SON和MDT
- 下一篇: java美元兑换,(Java实现) 美元