日期:2014-05-20  浏览次数:20719 次

java如何监听系统时间
比如让系统在整点通知我的java程序
打印一个时间


不用定时器,java如何实现?

------解决方案--------------------
没有直接的通知。

要么就是在操作系统做个定时任务,要么就是你的程序定时检查下当前时间(或者借助第三方包的定时任务,比如Quartz啥的)。
------解决方案--------------------
神马意思?
是系统到整点时间就启动一个java程序打印还是什么?
如果是这样,就设置系统的task,到整点调用java xxx 启动程序就可以了
如果是自己在程序里做整点通知,不用timer的话就用线程吧

------解决方案--------------------
Timer试试呢。
还有为什么不用windows的task来实现。
------解决方案--------------------
用Timer挺好的。
Java code


public class TimerDemo {
    
    /**
     * 得到下一个整点时间
     * @return
     */
    public static Date getNextFullTime(){
        Calendar calendar = Calendar.getInstance();
        Date date = null;
        if(calendar.get(Calendar.MINUTE) == 0 ){
            date =  calendar.getTime();
        }else{
            date =  new Date(calendar.get(Calendar.YEAR) - 1900, calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY) + 1, 0 , 0);
        }
        return date;
    }
    
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                JOptionPane.showMessageDialog(null, "时间到  " + new Date().toLocaleString());
            }
        }, TimerDemo.getNextFullTime() , 3600000);
    }
    
}

------解决方案--------------------
Timer和TimerTask可以实现