Question

I want to synchronise an action across multiple Android devices. For this I have a telnet client that I can send message to them.

Currently I send a message like DoWork On 1397131360435 to the devices. As you can notice the last argument is timestamp.

At the moment in my code I calculate the time difference between the given argument and use a TimerTask to call the method I want.

But this doesn't work exactly like I want because of influence of network delay and the time that this command arrives at devices is a bit different which results in few milliseconds of delay between devices.

Is there a way that I can wait for a specific timestamp and then run the method I want?

Currently I do like this:

 msDelay = Long.parseLong(args.get(2)) - System.currentTimeMillis();

               //inside a listener
               new java.util.Timer().schedule(
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                mySyncMethod();

                            }
                        },
                        msDelay
                );

So what I mean is, I want to run the mySincMethod when the timestamp is 1397131360435....not just its difference with local System.currentTimeMillis()

Was it helpful?

Solution

There is a saying: A man with a clock knows the time; a man with two clocks is forever uncertain...

There are a host of issues synchronizing deveices with milisecond accurracy: network latency, different per-device dates, different delays in devices starting these tasks... I'd suggest using Tim's method, but first

  • poll the devices 2-3 times to find out a) their network latency, b) their local time
  • poll the devices with a dummy task you want to execute (play a 0-length sound f.e. if you want to play sounds), and find out that delay
  • send to each device its own time to start based on the above.

OTHER TIPS

There are different Timer.schedule methods:

void schedule(TimerTask task, Date time) 
      Schedules the specified task for execution at the specified time.

void schedule(TimerTask task, long delay) 
      Schedules the specified task for execution after the specified delay.

You are using the latter currently. To make it work at the specified time, you should use the former by converting milliseconds to Date.

You can convert milliseconds to Date as follows:

long millis = 123456780000;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
Date date = calendar.getTime();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top