使用Java同步Linux服务器时间

本文介绍了如何在UOS系统遇到时间同步问题后,通过添加commons-net依赖并利用Java编写代码,调用NTP服务从阿里云获取时间戳,最终设置系统时间的过程。
摘要由CSDN通过智能技术生成

前言

公司客户线上服务器采用的是UOS系统,实施发现系统不会同步时间,并且时间有真实时间有偏差,本意想安装NTP授时服务,结果发现UOS安装NTP都要折腾好久,遂采用Java来曲线救国了。

添加依赖

<dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>3.10.0</version>
</dependency>

编写同步代码

public static void main(String[] args) throws IOException, InterruptedException {
    SpringApplication.run(TimeApplication.class, args);
    // 获取时区
    TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
    // 设置时区
    TimeZone.setDefault(timeZone);
    try (NTPUDPClient timeClient = new NTPUDPClient()) {
        // 定义阿里云ntp授时服务地址
        InetAddress timeServerAddress = InetAddress.getByName("ntp.aliyun.com");
        TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
        TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
        // 定义格式化时间格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区
        format.setTimeZone(timeZone);
        // 获取格式化时间
        String newTime = format.format(timeStamp.getTime());
        System.out.println("获取时间为: " + newTime);
        String timeCommand = "sudo date -s '" + newTime + "'";
        // 以root身份执行命令
        String[] command = {"/bin/sh", "-c", timeCommand};
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
        int exitValue = process.waitFor();
        if (exitValue == 0) {
            System.out.println("系统时间已设置为: " + newTime);
        } else {
            System.out.println("设置系统时间失败.");
        }
    }
}
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值