簡體   English   中英

安排常規任務而不擴展TimerTask?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM