温馨提示×

ubuntu定时器怎样延时

小樊
45
2026-10-12 20:30:36
栏目: 智能运维

在 Ubuntu(Linux)里,“定时器延时”通常有两层意思,我分开说,你看看你指的是哪种。


一、用 cron / at 做延时执行任务

1️⃣ at:最简单的一次性延时

at now + 5 minutes

然后输入要执行的命令,Ctrl+D 结束。

例子:

echo "touch /tmp/test.txt" | at now + 10 minutes

支持的单位:

  • minutes
  • hours
  • days
  • weeks

✅ 适合:几分钟后执行一次


2️⃣ sleep + cron(不太推荐但能用)

* * * * * sleep 30 && /path/script.sh

表示:每分钟触发,但延时 30 秒执行。

⚠️ 不精确,不推荐长期使用。


二、用 systemd 定时器(现代 Ubuntu 推荐)

场景:延时 1 分钟执行一次任务

1️⃣ 创建 service

# /etc/systemd/system/mytask.service
[Unit]
Description=My delayed task

[Service]
Type=oneshot
ExecStart=/path/to/script.sh

2️⃣ 创建 timer(延时启动)

# /etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask after delay

[Timer]
OnBootSec=1min
OnUnitActiveSec=1h
Persistent=true

[Install]
WantedBy=timers.target

启用:

systemctl daemon-reload
systemctl enable --now mytask.timer

常用延时参数:

  • OnBootSec=2min(开机后延时)
  • OnStartupSec=30s
  • OnCalendar=*-*-* 03:00:00(定点)

✅ 适合:系统级、精确、可管理


三、Shell 脚本里的“延时”

如果你只是写脚本:

sleep 5
echo "5秒后执行"

单位:

  • s 秒
  • m 分
  • h 小时

四、你可能是想问的

如果你说的是:

  • ✅ 开机后延时启动服务
  • ✅ 定时任务延迟几秒执行
  • ✅ systemd timer 怎么延时

告诉我具体场景,我可以给你现成配置模板。

0 踩