2010-02-25 36 views

回答

10

看看TimerTimerTask類。您可以安排一個線程在特定時間執行或重複執行。

public class Alarm { 
    Timer _timer; 

    public Alarm() { 

     // Create a Date corresponding to 10:30:00 AM today. 
     Calendar calendar = Calendar.getInstance(); 
     calendar.set(Calendar.HOUR_OF_DAY, 10); 
     calendar.set(Calendar.MINUTE, 30); 
     calendar.set(Calendar.SECOND, 0); 

     Date alarmTime = calendar.getTime(); 

     _timer = new Timer(); 
     _timer.schedule(new AlarmTask(), alarmTime); 
    } 

    class AlarmTask extends TimerTask { 
     /** 
     * Called on a background thread by Timer 
     */ 
     public void run() { 
      // Do your work here; it's 10:30 AM! 

      // If you don't want the alarm to go off again 
      // tomorrow (etc), cancel the timer 
      timer.cancel(); 
     } 
    } 
} 
+0

+1:更好地使用JDK的自定義 – akf 2010-02-25 05:07:51

4

的替代方法使用Quartz。它實際上與TimerTimerTask相同,但它確實允許描述必須使用cron樣式語法運行的內容。

+0

+1爲Quartz,cron樣式語法功能強大 – HeDinges 2010-02-25 08:25:52

3

由於Java 1.5有一個可取的方法,如果你需要更嚴格的:ScheduledThreadPoolExecutor

時需要多個工作線程,或者這個類是最好定時當額外的靈活性和能力ThreadPoolExecutor(該類擴展)是必需的。

scheduleAtFixedRate()scheduleWithFixedRate()之間可以選擇。關於使用的更多細節可以在鏈接的javadoc中找到。