温馨提示×

ubuntu定时器如何设置周期

小樊
39
2026-10-09 23:27:43
栏目: 智能运维

在 Ubuntu(及大多数 Linux 发行版)中,**“定时器”**通常有两种常见含义,下面分别说明:


一、使用 cron 设置周期性任务(最常用)

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

crontab -e

2️⃣ cron 周期格式

* * * * *  command
│ │ │ │ │
│ │ │ │ └─ 星期 (0-7, 0和7都代表周日)
│ │ │ └─── 月份 (1-12)
│ │ └───── 日期 (1-31)
│ └─────── 小时 (0-23)
└───────── 分钟 (0-59)

3️⃣ 常见示例

# 每分钟执行
* * * * * /home/user/test.sh

# 每小时整点
0 * * * * /home/user/test.sh

# 每天凌晨 2 点
0 2 * * * /home/user/backup.sh

# 每 5 分钟
*/5 * * * * /home/user/test.sh

# 每周一 8:30
30 8 * * 1 /home/user/test.sh

二、使用 systemd timer(更现代、更精确)

1️⃣ 创建 service

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

内容:

[Unit]
Description=My Timer Task

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

2️⃣ 创建 timer

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

内容示例(每 10 分钟):

[Unit]
Description=Run mytask every 10 minutes

[Timer]
OnCalendar=*:0/10
Persistent=true

[Install]
WantedBy=timers.target

3️⃣ 启用并启动

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

4️⃣ 查看状态

systemctl list-timers

三、一次性定时(补充)

# 10 分钟后执行
at now + 10 minutes

总结

方式 适合场景
cron 简单周期任务
systemd timer 精确、可依赖启动时间
at 一次性任务

如果你是 服务器 / 桌面 / 容器 环境,或想要 开机后延迟执行 / 固定时间窗口,可以告诉我,我给你更具体的配置。

0 踩