Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Event Listener on Clock Minute change

Tags:

java

timer

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

like image 362
DevilCode Avatar asked Dec 21 '22 18:12

DevilCode


1 Answers

  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();
    
like image 197
Charlie Avatar answered Dec 24 '22 03:12

Charlie