linux设备重启后时间与网络时间不同步怎么解决?
linux设备重启后时间与网络时间不同步怎么解决?
设备只要一重启,时间又错了/偏了,明明刚刚对时还是对的!
这在物联网、嵌入式开发环境特别常见,尤其是开发板、树莓派、rk3588 这类设备。
解决方法:
-
加硬件RTC+纽扣电池(行业唯一一劳永逸方案)
-
(推荐)建议你显式配置国内NTP服务器
编辑/etc/systemd/timesyncd.conf
,把[Time]
段下的 NTP= 改成国内可靠NTP
:[Time] NTP=ntp.aliyun.com ntp.tencent.com cn.pool.ntp.org FallbackNTP=ntp.ubuntu.com ntp1.aliyun.com
保存后重启 NTP 服务:
sudo systemctl restart systemd-timesyncd
然后确保
NTP service: active
,过一阵System clock synchronized: yes
:timedatectl status
当然,也可以写成一个 systemd service
让你的业务随系统启动自检(推荐用 systemd service)
可以保证每次开机自动跑等待时间同步的脚本/主程序,真正一劳永逸。
举例 /etc/systemd/system/my_ai_app.service
:
[Unit]
Description=AI Main App with NTP check
After=network-online.target[Service]
Type=simple
ExecStart=/bin/bash /home/start_ai_with_ntp_check.sh
Restart=on-failure[Install]
WantedBy=multi-user.target
其中 /home/heahu/start_ai_with_ntp_check.sh
:
#!/bin/bash
while true; doif timedatectl status | grep "System clock synchronized: yes" > /dev/null; thenbreakfiecho "等待NTP时间同步..."sleep 2
done
echo "时间已同步,启动主程序..."
python3 your_main_app.py
然后
sudo systemctl daemon-reload
sudo systemctl enable my_ai_app
sudo systemctl start my_ai_app