2015-04-14 26 views
0

我是Java的新手,我想製作一個程序,在檢測到時間時執行確定的操作。如何做一個計時器監聽器?

例子: 我啓動一個定時器,當30個SEGS已經走了,顯示一條消息,3分鐘後都走了,執行其它的動作,等等,等等

我怎樣才能做到這一點?

謝謝

+1

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger –

回答

0

使用Timer類,你可以做這樣的事情:

public void timer() { 

    TimerTask tasknew = new MyTask(); 
    Timer timer = new Timer(); 

    /* scheduling the task, the first argument is the task you will be 
    performing, the second is the delay, and the last is the period. */ 
    timer.schedule(tasknew, 100, 100); 
} 

}

這是一個擴展的TimerTask並做了一個類的實例。

class MyTask extends TimerTask { 

     @Override 
     public void run() { 
      System.out.println("Hello world from Timer task!"); 

     } 
    } 

進一步的閱讀調查

Timer Docs

Timer schedule example

0

使用ScheduledExecutorService是一種可能性。

請參閱the docs for usage example and more

import static java.util.concurrent.TimeUnit.*; 
class BeeperControl { 
    private final ScheduledExecutorService scheduler = 
     Executors.newScheduledThreadPool(1); 

    public void beepForAnHour() { 
     final Runnable beeper = new Runnable() { 
      public void run() { System.out.println("beep"); } 
     }; 
     final ScheduledFuture<?> beeperHandle = 
      scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); 
     scheduler.schedule(new Runnable() { 
      public void run() { beeperHandle.cancel(true); } 
     }, 60 * 60, SECONDS); 
    } 
}