Larx
Larx

Reputation: 161

How to get time in nanoseconds from external webservice in Java?

Is there a webservice that returns time to the point of nanoseconds that can be called from java? I need an external source that give me time. Locally in my java application I called System.nanoTime(); but I need to call the time from a server for other calculations.

Thanks

Upvotes: 1

Views: 413

Answers (1)

pedrofb
pedrofb

Reputation: 39241

The Network Time Protocol (NTP) allow to sync clocks of computer systems. You can connect to any NTP server to request the current time

NTPUDPClient in package apache commons provides an NTP client

usage

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;


public long getRemoteNTPTime() {
    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 5 seconds
    client.setDefaultTimeout(5000);
    //NTP server list
    for (String host : hosts) {

        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            TimeInfo info = client.getTime(hostAddr);
            return info.getMessage().getTransmitTimeStamp().getTime();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    client.close();

    return null;

}

Configure several hosts to avoid if one is down. Look for servers near your hosting to reduce network latency. For example

ntp02.oal.ul.pt 
ntp04.oal.ul.pt 
ntp.xs4all.nl

Upvotes: 1

Related Questions