文章目录
前言
项目开发过程中,业务要求,一台电脑,要根据另一台电脑实时同步时间
运行环境
window10 64位系统
jdk 1.8
一、服务端
服务端启动,通过修改系统注册表,启动NTP服务,作为时间同步服务器。
代码如下(示例):
import java.io.IOException;
class Scratch {
public static void main(String[] args) {
String startNtpServer = "REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\W32Time\\TimeProviders\\NtpServer /v Enabled /t REG_DWORD /d 1 /f";
//TODO 设置为“5”,表示强制主机将它自身宣布为可靠的时间源
String execute2 = "REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\W32Time\\Config /v AnnounceFlags /t REG_DWORD /d 5 /f";
String stopW32Time = "net stop w32Time";
String startW32Time = "net start w32Time";
try {
Runtime.getRuntime().exec(startNtpServer);
Thread.sleep(100);
Runtime.getRuntime().exec(execute2);
Thread.sleep(100);
Runtime.getRuntime().exec(stopW32Time);
Thread.sleep(100);
Process exec = Runtime.getRuntime().exec(startW32Time);
int res = exec.waitFor();
if (res != 0) {
System.out.println("fail");
} else {
System.out.println("success");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
二、客户端
客户端启动,通过修改系统注册表,设置时间同步服务器地址,时间同步间隔。
代码如下(示例):
import java.io.IOException;
class Scratch {
public static void main(String[] args) {
String host = "192.168.1.100";
//设置时间同步间隔
String setInterval = "REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\W32Time\\TimeProviders\\NtpClient /v SpecialPollInterval /t REG_DWORD /d 10 /f";
//添加时间同步服务器列表
String addTimeHost = "REG ADD HKEY_LOCAL_MACHINE\\SOFTWARE\\MICROSOFT\\WINDOWS\\CURRENTVERSION\\DATETIME\\SERVERS /v 3 /t REG_SZ /d \"" + host + "\" /f";
String setTimeHost = "REG ADD HKEY_LOCAL_MACHINE\\SOFTWARE\\MICROSOFT\\WINDOWS\\CURRENTVERSION\\DATETIME\\SERVERS /ve /t REG_SZ /d 3 /f";
//设置时间同步服务器地址
String setParameter = "REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\W32Time\\Parameters /v NtpServer /t REG_SZ /d \"" + host + ",0x9\" /f";
String stopW32Time = "net stop w32Time";
String startW32Time = "net start w32Time";
try {
Runtime.getRuntime().exec(addTimeHost);
Thread.sleep(100);
Runtime.getRuntime().exec(setTimeHost);
Thread.sleep(100);
Runtime.getRuntime().exec(setInterval);
Thread.sleep(100);
Runtime.getRuntime().exec(setParameter);
Thread.sleep(100);
Runtime.getRuntime().exec(stopW32Time);
Thread.sleep(100);
Process exec = Runtime.getRuntime().exec(startW32Time);
int res = exec.waitFor();
if (res != 0) {
System.out.println("fail");
} else {
System.out.println("success");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}