Browse Source

fix:修改时间前先关闭自动时间同步

master
白凤吉 2 weeks ago
parent
commit
ceace3b0f9
  1. 27
      src/main/java/com/qyft/ms/app/service/SystemService.java

27
src/main/java/com/qyft/ms/app/service/SystemService.java

@ -4,7 +4,10 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
/**
@ -30,24 +33,34 @@ public class SystemService {
*/
public void setSystemTime(long epochMilli) {
long epochSecond = epochMilli / 1_000;
runCommand("timedatectl", "set-ntp", "false");
runCommand("date", "-s", "@" + epochSecond);
runCommand("hwclock", "--systohc");
}
/**
* 辅助执行系统命令并检查退出码
*/
private void runCommand(String... cmd) {
private String runCommand(String... cmd) {
try {
log.info("CMD: {}", String.join(" ", cmd));
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.inheritIO();
pb.environment().put("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
pb.redirectErrorStream(true);
Process p = pb.start();
StringBuilder out = new StringBuilder();
try (BufferedReader r = new BufferedReader(
new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = r.readLine()) != null) {
out.append(line).append('\n');
}
}
int exit = p.waitFor();
if (exit != 0) {
throw new IllegalStateException(
String.format("命令 %s 执行失败,退出码=%d", String.join(" ", cmd), exit)
);
String.format("命令执行失败: [%s], 退出码=%d, 输出=\n%s",
String.join(" ", cmd), exit, out));
}
return out.toString();
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("执行系统命令失败: " + String.join(" ", cmd), e);

Loading…
Cancel
Save