2

I have to show multiple clocks in screen from different places like New Delhi, Hong Kong, Frankfurt, Washington, etc. And these times are changing like any other real clock but as Time-Left to a fixed date-time and they are added to the screen at different moments as the user adds them. For example:

New Delhi       1d 4h 20 min 5s
Hong Kong       9h 2min 55s
Washington      22min 3s
...

I have a Class which makes all the calculations to get those times in that format. The problem comes when these times are shown on screen. How do I make them to update their time at the same time? So all the changes in the seconds are shown at the same time. I know it won't be theoretically at the same time, but the most close to it. This is the timer I am using:

Timer t = new Timer();   
t.scheduleAtFixedRate(
    new TimerTask()
    {
        public void run() {
          Platform.runLater(new Runnable() {
              @Override
              public void run() {
                  label[id].setText(getTimeLeft(id));
              }
          });
        }
    },
    0,      // run first occurrence immediately
    1000);  // run every seconds

Also, some of them freeze eventually. Does any body knows why?

Joe Almore
  • 4,036
  • 9
  • 52
  • 77

1 Answers1

5

How do I make them to update their time at the same time? So all the changes in the seconds are shown at the same time. I know it won't be theoretically at the same time, but the most close to it. This is the timer I am using:

Instead of using separate Timers for each label, use a single Timer for ALL the labels

Timer t = new Timer();   
t.scheduleAtFixedRate(
    new TimerTask()
    {
        public void run() {
          Platform.runLater(new Runnable() {
              @Override
              public void run() {
                  for (int id = 0; id < label.length; id++) {
                      label[id].setText(getTimeLeft(id));
                  }
              }
          });
        }
    },
    0,      // run first occurrence immediately
    1000);  // run every seconds

This will reduce the overhead of resources on you system (one timer instead of n times), possible event queue spamming as multiple timers trigger simultaneously and allow the times to "seem" to update at the same time, as they are all updated within the event queue, so they won't update until the next paint cycle, which won't happen until you exit the run block...

You could also make use Timeline, which would reduce the need for Platform.runLater, see How to update the label box every 2 seconds in java fx? for an example.

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Yes, this approach works very well. Now the transition from one second to another is instantly, it is unnoticeable at simple sight. – Joe Almore Sep 04 '15 at 02:51