在 Ubuntu 中,“定时器”最常见的是 systemd 的 timer(推荐、服务器常用),也可以是传统的 cron。下面分别说明如何启用。
例如 /etc/systemd/system/mytask.service:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello from timer"
例如 /etc/systemd/system/mytask.timer:
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
systemctl list-timers
systemctl status mytask.timer
✅ 这样就启用了 systemd 定时器。
crontab -e
例如每天凌晨 2 点执行:
0 2 * * * /path/to/script.sh
sudo systemctl enable --now cron
systemd timercronsystemd如果你愿意,可以告诉我:
我可以直接帮你写好配置。