温馨提示×

ubuntu定时器如何开机启动

小樊
47
2026-09-25 08:02:46
栏目: 智能运维

在 Ubuntu 中,“定时器”通常指 systemd timer(类似 cron,但更现代)。要让 定时器在开机后自动启动,核心思路是:

enable timer 单元(不是 start)

下面分情况说明。


一、使用 systemd timer(推荐方式)

1️⃣ 创建 service(任务本体)

例如 /etc/systemd/system/mytask.service:

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello"

2️⃣ 创建 timer(定时器)

例如 /etc/systemd/system/mytask.timer:

[Unit]
Description=Run My Task Timer

[Timer]
OnBootSec=1min
OnUnitActiveSec=1h

[Install]
WantedBy=timers.target

3️⃣ 设置开机启动(关键)

sudo systemctl daemon-reload
sudo systemctl enable mytask.timer

✅ enable 会创建开机自启符号链接
❌ 不要用 start,那只是当前会话运行

4️⃣ 查看状态

systemctl list-timers
systemctl status mytask.timer

二、使用 cron(传统方式)

如果只是“开机运行一次”:

crontab -e

添加:

@reboot /path/to/script.sh

⚠️ 注意:

  • 需要系统开机后 cron 服务正常运行
  • 不适合复杂调度

三、rc.local(不推荐但可用)

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

如果你愿意,可以告诉我:

  • 是 用户级还是系统级
  • 是 周期性任务还是开机一次
  • Ubuntu 版本(20.04 / 22.04 / 24.04)

我可以帮你写完整可直接用的配置。

0 踩