温馨提示×

ubuntu定时器怎么开机启动

小樊
40
2026-09-28 06:15:43
栏目: 智能运维

在 Ubuntu 里“开机启动定时器”通常分两种常见场景,下面分别说明:


一、使用 systemd 定时器(推荐 ✅)

如果你用的是 systemd 定时器(.timer),它本身就可以设置开机启动。

1️⃣ 创建 service(示例)

sudo vim /etc/systemd/system/mytask.service

内容:

[Unit]
Description=My Task

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

2️⃣ 创建 timer

sudo vim /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

✅ 这样 开机后定时器会自动启动

查看状态:

systemctl list-timers
systemctl status mytask.timer

二、使用 cron @reboot(简单方式)

如果你只是想在 开机时执行一次脚本:

crontab -e

添加:

@reboot /path/to/script.sh

⚠ 注意:

  • 脚本要有可执行权限
  • 环境变量可能不全(建议用绝对路径)

三、旧方式(不推荐):rc.local

Ubuntu 20.04+ 默认没有 rc.local

如必须使用:

sudo systemctl enable rc-local

总结建议

方式 推荐度 说明
systemd timer ⭐⭐⭐⭐⭐ 正式、可控
cron @reboot ⭐⭐⭐ 简单任务
rc.local ⭐ 老旧

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

  • 你是 定时器还是脚本
  • Ubuntu 版本
  • 想“开机启动”还是“定时执行”

我可以给你更精确的配置示例。

0 踩