在 Ubuntu 里“开机启动定时器”通常分两种常见场景,下面分别说明:
如果你用的是 systemd 定时器(.timer),它本身就可以设置开机启动。
sudo vim /etc/systemd/system/mytask.service
内容:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello"
sudo vim /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
✅ 这样 开机后定时器会自动启动
查看状态:
systemctl list-timers
systemctl status mytask.timer
如果你只是想在 开机时执行一次脚本:
crontab -e
添加:
@reboot /path/to/script.sh
⚠ 注意:
Ubuntu 20.04+ 默认没有 rc.local
如必须使用:
sudo systemctl enable rc-local
| 方式 | 推荐度 | 说明 |
|---|---|---|
| systemd timer | ⭐⭐⭐⭐⭐ | 正式、可控 |
| cron @reboot | ⭐⭐⭐ | 简单任务 |
| rc.local | ⭐ | 老旧 |
如果你愿意,可以告诉我:
我可以给你更精确的配置示例。