温馨提示×

ubuntu定时器如何创建

小樊
39
2026-09-19 05:09:37
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有两种理解:

  1. 一次性或周期性的任务调度(cron / at)
  2. Systemd 定时器(systemd timer,类似 Windows 计划任务)

下面分别说明。


一、使用 cron(最常用)

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

crontab -e

2️⃣ 添加定时任务格式

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

示例:

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

# 每 5 分钟执行一次
*/5 * * * * /usr/bin/python3 /home/user/task.py

3️⃣ 查看已有任务

crontab -l

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

sudo nano /etc/crontab

二、使用 at(一次性定时)

1️⃣ 安装 at

sudo apt install at
sudo systemctl enable --now atd

2️⃣ 创建一次性任务

at 02:00
at> /home/user/backup.sh
at> Ctrl+D

3️⃣ 查看任务

atq

4️⃣ 删除任务

atrm 任务编号

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

1️⃣ 创建 service

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

内容:

[Unit]
Description=My Task

[Service]
ExecStart=/home/user/task.sh

2️⃣ 创建 timer

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

内容:

[Unit]
Description=Run mytask daily

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

[Install]
WantedBy=timers.target

3️⃣ 启用定时器

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

4️⃣ 查看状态

systemctl list-timers

四、图形界面(桌面版 Ubuntu)

可用:

gnome-schedule

sudo apt install gnome-schedule

总结建议

场景 推荐方式
简单周期任务 cron
一次性任务 at
系统服务级 systemd timer

如果你有具体需求(比如每天几点、执行什么命令),我可以直接帮你写配置。

0