问题
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:
- Find the current system time using System.currentTimeMillis()
- Calculate how many milliseconds until the next minute
- Schedule a TimerTask on a Timer to run in that number of milliseconds in the future
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