2017-07-24 220 views
-1

我正在嘗試定期執行任務。例如:定時器無法執行任務

class MyTimerTask implements TimerTask 
{ 
    public void run() { 
    // Some actions to perform 
    } 
    Timer cleaner = new Timer(true); 
    cleaner.scheduleAtFixedRate(new MyTimerTask(), 0, PURGE_INTERVAL); 
} 

但是,run方法只執行一次。但是如果我第一次延遲10秒,那麼run方法甚至不會執行一次。

例子:

cleaner.scheduleAtFixedRate(new MyTimerTask(), 10, PURGE_INTERVAL); 

回答

0

這聽起來像是一個時間單位給我的問題。確保您正確轉換爲毫秒。

最簡單的方法是使用Java的TimeUnit

Timer cleaner = new Timer(true); 
cleaner.scheduleAtFixedRate(new MyTimerTask(), 
    TimeUnit.SECONDS.toMillis(10), 
    TimeUnit.SECONDS.toMillis(30)); 

它也被Timer引起正在啓動在守護進程模式。如果你所有的主要方法都設置了定時器,然後返回,定時器將永遠不會執行,因爲它是剩餘的最後一個線程,因爲它是一個守護進程線程,JVM將退出。

要解決這個問題,要麼使計時器線程不是守護進程(即在構造函數中傳遞false),要麼讓主線程在退出之前等待用戶輸入。

下面是使用兩種以上的例子:

public class TimerDemo extends TimerTask { 

    public void run() { 
     System.out.printf("Time is now %s%n", LocalTime.now()); 
    } 

    public static void main(String[] args) throws IOException { 
     Timer timer = new Timer(true); 
     timer.scheduleAtFixedRate(new TimerDemo(), 
       TimeUnit.SECONDS.toMillis(5), 
       TimeUnit.SECONDS.toMillis(10)); 
     System.out.printf("Program started at %s%n", LocalTime.now()); 
     System.out.println("Press enter to exit"); 
     try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { 
      // Wait for user to press enter 
      reader.readLine(); 
     } 
     System.out.println("Bye!"); 
    } 
} 

並運行它的輸出:

Program started at 14:49:42.207 
Press enter to exit 
Time is now 14:49:46.800 
Time is now 14:49:56.799 
Time is now 14:50:06.799 
Time is now 14:50:16.799 
Time is now 14:50:26.799 
[I pressed 'enter'] 
Bye! 

Process finished with exit code 0 
+0

是的,你是對的Raniz。問題出在從main方法退出run方法不執行之後。所以,我必須把睡眠放在主線程中。 –

+0

如果它解決了您的問題,請隨時接受我的答案。它通過在搜索結果中解決這個問題來幫助他人。 – Raniz

0

我有一個很難搞清楚究竟什麼是你的問題,所以這可能不是你問什麼了,但這種方法可能適合你:

public class MyTimerTask implements Runnable { 
    private static final TimeUnit timeUnit = TimeUnit.SECONDS; 
    private final ScheduledExecutorService scheduler; 
    private final int period = 10; 
    public static void main(String[] args) { 
     new MyTimerTask(); 
    } 
    public MyTimerTask() { 
     scheduler = Executors.newScheduledThreadPool(1); 
     scheduler.scheduleAtFixedRate(this, period, period, timeUnit); 
    } 
    @Override 
    public void run() { 
     // This will run every 10 seconds 
     System.out.println("Ran..."); 
    } 
} 
+0

所以是一個缺少@Override? – user7294900

+0

那麼,你能舉出一個「工作」的例子,因爲你提供的代碼不能運行,你在類聲明等語句中。我不認爲這就是爲什麼,因爲它只是一個註釋,讓編譯器給你更好的幫助。 – Lurr

相關問題