Java Event Listener on Clock Minute change

别等时光非礼了梦想. 提交于 2019-12-21 19:59:23

问题


I am looking for the best way in Java to monitor the computer clock (the minutes) and to fire off a method/thread every time it changes.

So if the time is 13:20 and it changes to 13.21 then do something. So any time there is a minute change some code gets fired.

What is the best way to listen to the minute section of the clock for changes ?

Thanks, Richard


回答1:


Date d = new Date(System.currentTimeMillis());

Then you can get the minutes by d.getMinutes(). Have a check running in a thread waiting for the value of d.getMinutes() to change.




回答2:


  1. Find the current system time using System.currentTimeMillis()
  2. Calculate how many milliseconds until the next minute
  3. Schedule a TimerTask on a Timer to run in that number of milliseconds in the future
  4. In that TimerTask's event handler schedule a new reoccurring TimerTask to run every 60,000 milliseconds.

    int milisInAMinute = 60000;
    long time = System.currentTimeMillis();
    
    Runnable update = new Runnable() {
        public void run() {
            // Do whatever you want to do when the minute changes
        }
    };
    
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            update.run();
        }
    }, time % milisInAMinute, milisInAMinute);
    
    // This will update for the current minute, it will be updated again in at most one minute.
    update.run();
    



回答3:


Sounds like a job for Quartz. You can do this using the following cron expression:

0 * * * * ?



来源:https://stackoverflow.com/questions/11635155/java-event-listener-on-clock-minute-change

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!