在 Debian 系统中,你可以使用 systemd
的定时器(timers)来同步时间。以下是具体步骤:
首先,确保你的系统上安装了 NTP 服务。如果没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install ntp
安装完成后,启用并启动 NTP 服务:
sudo systemctl enable ntp
sudo systemctl start ntp
接下来,创建一个 systemd 定时器来定期同步时间。你可以使用 timedatectl
命令来配置时间同步。
编辑 /etc/systemd/timesyncd.conf
文件,设置时间同步的频率。例如,每 15 分钟同步一次时间:
[Time]
NTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org
FallbackNTP=ntp.ubuntu.com
保存文件后,重新加载 systemd 配置:
sudo systemctl daemon-reload
创建一个新的 systemd 定时器单元文件,例如 /etc/systemd/system/ntp-sync.timer
:
[Unit]
Description=Run ntpdate every 15 minutes
[Timer]
OnCalendar=*:0/15
Persistent=true
[Install]
WantedBy=timers.target
这个定时器会在每小时的每个 15 分钟触发一次。
创建一个对应的服务单元文件,例如 /etc/systemd/system/ntp-sync.service
:
[Unit]
Description=Sync system time with NTP server
[Service]
Type=oneshot
ExecStart=/usr/sbin/ntpdate -u 0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org
这个服务会执行 ntpdate
命令来同步时间。
启用并启动你刚刚创建的定时器:
sudo systemctl enable ntp-sync.timer
sudo systemctl start ntp-sync.timer
你可以使用以下命令检查定时器的状态:
sudo systemctl list-timers --all
你应该能看到 ntp-sync.timer
正在运行,并且按照设定的时间间隔触发。
通过以上步骤,你就可以在 Debian 系统中使用 systemd 定时器来同步时间了。