![](/img/trans.png)
[英]How to schedule a task at regular intervals without using threads in Java?
[英]Schedule regular task without extending TimerTask?
如何在單獨的線程和給定的間隔中重復運行此類的實例? (您已經注意到我正在使用Java 2 EE)。
public class Gate extends AbsDBObject<Gate> implements Runnable{
public void Run(){
//Something
}
}
我之前通過Gate
類擴展TimerTask
類並使用Timer
來完成此操作:
Timer timer = new Timer();
Gate gates = Gate.fetchOne();
timer.schedule(gate, 0, 1000);
但是在這種情況下,我無法擴展任何其他類。 我該怎么辦?
如果使用ScheduledExecutorService
則只需執行Runnable
對象,而不是TimerTask
對象。
ScheduledExecutorService executorService =
new ScheduledThreadPoolExecutor(corePoolSize);
Gate gate = Gate.fetchOne();
executorService.scheduleAtFixedRate(gate, 0, 1, TimeUnit.SECONDS);
這樣就無需擴展。
嘗試
Timer timer = new Timer();
final Gate gates = Gate.fetchOne();
timer.schedule(new TimerTask() {
public void run() {
gates.run();
}
}, 0, 1000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.