前言
公司客户线上服务器采用的是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("设置系统时间失败.");
}
}
}