在 Ubuntu(Linux)里,“定时器延时”通常有两层意思,我分开说,你看看你指的是哪种。
cron / at 做延时执行任务at:最简单的一次性延时at now + 5 minutes
然后输入要执行的命令,Ctrl+D 结束。
例子:
echo "touch /tmp/test.txt" | at now + 10 minutes
支持的单位:
✅ 适合:几分钟后执行一次
sleep + cron(不太推荐但能用)* * * * * sleep 30 && /path/script.sh
表示:每分钟触发,但延时 30 秒执行。
⚠️ 不精确,不推荐长期使用。
systemd 定时器(现代 Ubuntu 推荐)# /etc/systemd/system/mytask.service
[Unit]
Description=My delayed task
[Service]
Type=oneshot
ExecStart=/path/to/script.sh
# /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=30sOnCalendar=*-*-* 03:00:00(定点)✅ 适合:系统级、精确、可管理
如果你只是写脚本:
sleep 5
echo "5秒后执行"
单位:
s 秒m 分h 小时如果你说的是:
告诉我具体场景,我可以给你现成配置模板。