温馨提示×

ubuntu定时器怎样管理

小樊
35
2026-09-25 08:03:45
栏目: 智能运维

在 Ubuntu 中,“定时器”通常有两种常见含义,下面分别说明管理方式:


一、使用 systemd 定时器(推荐,服务器/后台任务)

Ubuntu 16.04 以后默认使用 systemd,可以用 .timer 单元来管理定时任务,功能类似 cron,但更强大。

1. 基本概念

  • .service:要执行的任务
  • .timer:控制什么时候执行

2. 创建一个定时器示例

sudo mkdir -p /etc/systemd/system

编辑 service 文件:

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

内容:

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello"

编辑 timer 文件:

sudo nano /etc/systemd/system/mytask.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 mytask.timer

常用命令:

systemctl list-timers          # 查看所有定时器
systemctl status mytask.timer  # 查看状态
systemctl stop mytask.timer    # 停止
systemctl start mytask.timer   # 启动
systemctl disable mytask.timer # 取消开机启动

二、使用 crontab(传统方式)

适合简单的周期性任务。

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

crontab -e

示例(每天 2 点执行):

0 2 * * * /path/to/script.sh

2. 查看和管理

crontab -l        # 查看
crontab -r        # 删除

3. 系统级 cron

/etc/crontab
/etc/cron.d/

三、一次性定时任务(at)

适合“几分钟后执行一次”。

sudo apt install at
echo "shutdown -h now" | at now + 10 minutes

查看:

atq

删除:

atrm 任务号

四、如何选择?

  • ✅ 后台服务 / 系统任务 → systemd timer
  • ✅ 简单脚本 → crontab
  • ✅ 临时一次任务 → at

如果你有具体使用场景(比如“每天备份”“开机运行”“失败重试”),我可以帮你写完整配置。

0 踩