温馨提示×

ubuntu定时器怎样设置周期

小樊
36
2026-10-18 17:50:13
栏目: 智能运维

在 Ubuntu 里“定时器”通常有两种常见含义,下面分别说明如何设置周期:


一、使用 systemd 定时器(推荐,服务器/现代 Ubuntu)

这是 Ubuntu 16.04 以后最标准的方式。

1️⃣ 创建 service(要执行的任务)

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

内容示例:

[Unit]
Description=My Task

[Service]
Type=simple
ExecStart=/usr/bin/bash /opt/mytask.sh

2️⃣ 创建 timer(定时规则)

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

常见周期示例:

每 10 分钟执行一次

[Unit]
Description=Run mytask every 10 min

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

[Install]
WantedBy=timers.target

每天 3:30 执行

OnCalendar=*-*-* 03:30:00

每周一 02:00

OnCalendar=Mon *-*-* 02:00:00

每小时

OnCalendar=hourly

3️⃣ 启用并启动

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

4️⃣ 查看状态

systemctl list-timers
systemctl status mytask.timer

二、使用 crontab(传统方式)

编辑当前用户定时任务

crontab -e

周期格式

分 时 日 月 星期 命令

示例:

每 5 分钟

*/5 * * * * /opt/mytask.sh

每天 2:30

30 2 * * * /opt/mytask.sh

每周日 0 点

0 0 * * 0 /opt/mytask.sh

每 1 小时

0 * * * * /opt/mytask.sh

查看已有任务

crontab -l

三、如何选择?

场景 推荐
系统服务、需要日志 ✅ systemd timer
简单脚本、快速 ✅ crontab
需要开机自动运行 两者都可

如果你愿意,可以告诉我:

  • Ubuntu 版本
  • 想“每隔多久”执行
  • 是系统任务还是用户任务

我可以帮你写一份可直接用的配置。

0 踩