温馨提示×

ubuntu定时器能每分钟跑吗

小樊
46
2026-09-22 07:15:24
栏目: 智能运维

可以的,Ubuntu 下常见的“定时器”有两种主流方案,都能做到每分钟执行一次:


一、cron(最常用、最简单)

Ubuntu 默认带 cron,支持最小粒度为 1 分钟。

每分钟执行一次

* * * * * /path/to/your/script.sh

编辑当前用户的 cron

crontab -e

查看 cron 是否运行

sudo systemctl status cron

⚠️ cron 最小只能到分钟,不能每秒执行。


二、systemd timer(更现代)

如果你用的是 systemd(Ubuntu 16.04+ 基本都是),可以用 timer。

1. 创建 service

/etc/systemd/system/mytask.service

[Unit]
Description=My Task

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

2. 创建 timer(每分钟)

/etc/systemd/system/mytask.timer

[Unit]
Description=Run my task every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min

[Install]
WantedBy=timers.target

3. 启用

sudo systemctl daemon-reexec
sudo systemctl enable --now mytask.timer

查看状态

systemctl list-timers

三、如果你想要「每秒」执行?

cron 和 systemd timer 都不直接支持每秒
常见做法:

  • 在脚本里用 sleep 1 循环
  • 或用 watch -n 1 command

总结

✅ Ubuntu 定时器可以每分钟跑
✅ 推荐:简单任务用 cron
✅ 复杂/系统级任务用 systemd timer

如果你愿意,我可以帮你写一个具体例子(比如日志清理、健康检查等)。

0 踩