2010-02-25 35 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中找到。