繁体   English   中英

如何从Java中的外部Web服务获取时间(以纳秒为单位)?

[英]How to get time in nanoseconds from external webservice in Java?

是否有一个Web服务可以将时间返回到可以从Java调用的纳秒点? 我需要给我时间的外部资源。 在我的Java应用程序本地,我调用了System.nanoTime();。 但是我需要从服务器调用时间进行其他计算。

谢谢

网络时间协议(NTP)允许同步计算机系统的时钟。 您可以连接到任何NTP服务器以请求当前时间

apache commons包中的NTPUDPClient提供NTP客户端

用法

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;

}

配置多台主机,以避免主机宕机。 在主机附近寻找服务器以减少网络延迟。 例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM