在 Ubuntu 中,“定时器”通常指 systemd timer(类似 cron,但更现代)。要让 定时器在开机后自动启动,核心思路是:
enable timer 单元(不是 start)
下面分情况说明。
例如 /etc/systemd/system/mytask.service:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello"
例如 /etc/systemd/system/mytask.timer:
[Unit]
Description=Run My Task Timer
[Timer]
OnBootSec=1min
OnUnitActiveSec=1h
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable mytask.timer
✅ enable 会创建开机自启符号链接
❌ 不要用 start,那只是当前会话运行
systemctl list-timers
systemctl status mytask.timer
如果只是“开机运行一次”:
crontab -e
添加:
@reboot /path/to/script.sh
⚠️ 注意:
sudo nano /etc/rc.local
/path/to/script.sh &
exit 0
并确保:
sudo systemctl enable rc-local
❌ 只 start 不 enable → 重启后失效
❌ 放在 ~/.bashrc → 只限用户登录
❌ 用 sleep 写死时间 → 不稳定
Ubuntu 定时器开机启动 = systemd timer +
systemctl enable xxx.timer
如果你愿意,可以告诉我:
我可以帮你写完整可直接用的配置。