在 Debian 系统中,你可以使用 systemd 的定时器(timers)来同步时间。以下是具体步骤:
首先,确保你的系统上安装了 NTP 服务。你可以使用以下命令来安装:
sudo apt update
sudo apt install ntp
安装完成后,启用并启动 NTP 服务:
sudo systemctl enable ntp
sudo systemctl start ntp
接下来,创建一个 systemd 定时器来定期同步时间。你可以使用 timedatectl 命令来设置定时器。
创建一个新的定时器单元文件,例如 /etc/systemd/timers/ntp-sync.timer:
sudo nano /etc/systemd/timers/ntp-sync.timer
在文件中添加以下内容:
[Unit]
Description=Run ntpdate every hour
[Timer]
OnCalendar=*-*-* *:00:00
Persistent=true
[Install]
WantedBy=timers.target
这个定时器会在每小时的第 0 分钟运行一次 ntpdate 命令。
创建一个对应的服务单元文件,例如 /etc/systemd/system/ntp-sync.service:
sudo nano /etc/systemd/system/ntp-sync.service
在文件中添加以下内容:
[Unit]
Description=Sync system time with NTP server
[Service]
Type=oneshot
ExecStart=/usr/sbin/ntpdate pool.ntp.org
这个服务单元文件定义了定时器运行时要执行的命令。
启用并启动刚刚创建的定时器:
sudo systemctl enable ntp-sync.timer
sudo systemctl start ntp-sync.timer
你可以使用以下命令来检查定时器的状态:
sudo systemctl list-timers --all
你应该能看到 ntp-sync.timer 的状态为 active (running)。
最后,验证时间是否已经同步:
timedatectl status
你应该能看到系统时间已经同步到 NTP 服务器的时间。
通过以上步骤,你就可以在 Debian 系统中使用 systemd 定时器来定期同步时间了。