温馨提示×

ubuntu定时器如何定时

小樊
38
2026-09-25 07:58:45
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有两种常见实现方式:

  1. cron:最常用的定时任务(按分钟/小时/天等周期执行)
  2. systemd timer:更现代、更强大的定时方式(类似 Windows 计划任务)

下面分别说明。


一、使用 cron(最常用)

1️⃣ 编辑当前用户的定时任务

crontab -e

2️⃣ 添加定时任务格式

* * * * * command
分 时 日 月 周  命令

示例:

# 每天凌晨 2 点执行备份脚本
0 2 * * * /home/user/backup.sh

# 每 5 分钟执行一次
*/5 * * * * /home/user/check.sh

# 每周一 9:30
30 9 * * 1 /home/user/weekly.sh

3️⃣ 查看已有任务

crontab -l

4️⃣ 系统级 cron(所有用户)

sudo nano /etc/crontab

二、使用 systemd timer(推荐服务器使用)

1️⃣ 创建服务文件

sudo nano /etc/systemd/system/mytimer.service

内容:

[Unit]
Description=My Timer Task

[Service]
Type=oneshot
ExecStart=/home/user/myscript.sh

2️⃣ 创建 timer 文件

sudo nano /etc/systemd/system/mytimer.timer

内容:

[Unit]
Description=Run my task daily

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

3️⃣ 启用并启动

sudo systemctl daemon-reload
sudo systemctl enable --now mytimer.timer

4️⃣ 查看状态

systemctl list-timers

三、临时延迟执行(一次性)

at now + 1 hour

或

sleep 3600 && ./script.sh

四、如何选择?

  • ✅ 简单周期任务 → cron
  • ✅ 需要日志、依赖、精确控制 → systemd timer

如果你能说明:

  • 是 用户级还是系统级
  • 想 多久执行一次
  • 执行 什么命令/脚本

我可以直接帮你写配置。

0 踩