2012-07-10 63 views

回答

9

使用java.util.Timer.scheduleAtFixedRate()java.util.TimerTask是一個可能的解決方案:

Timer t = new Timer(); 

t.scheduleAtFixedRate(
    new TimerTask() 
    { 
     public void run() 
     { 
      System.out.println("hello"); 
     } 
    }, 
    0,  // run first occurrence immediatetly 
    2000)); // run every two seconds 
+0

不錯,雖然javax.swing.Timer中如果Fisol RASEL使用很多,如果應用程序 – 2012-07-10 15:20:53

6

爲了反覆,你需要使用某種形式的線程的,在後臺運行調用一個方法。我推薦使用ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); 
exec.scheduleAtFixedRate(new Runnable() { 
      public void run() { 
       // code to execute repeatedly 
      } 
     }, 0, 60, TimeUnit.SECONDS); // execute every 60 seconds 
+0

這是否工作,甚至Swing組件可能是一個更好的選擇被殺了? – 2015-04-25 07:21:48

+0

@VNJ:不,如果父進程被終止,工作線程就不能存在。 – Tudor 2015-04-27 09:52:05

+0

那該如何實現呢? – 2015-04-27 10:14:34

0

擺動計時器也是一個不錯的主意來實現重複函數調用。

Timer t = new Timer(0, null); 

t.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
      //do something 
    } 
}); 

t.setRepeats(true); 
t.setDelay(1000); //1 sec 
t.start(); 
相關問題