温馨提示×

ubuntu定时器怎么配置时间

小樊
42
2026-10-01 04:19:03
栏目: 智能运维

在 Ubuntu 里“定时器”通常指两类东西,先说明一下,然后分别讲怎么配时间:


一、系统级定时任务:cron(最常用)

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

crontab -e

2️⃣ cron 时间格式

分 时 日 月 周 命令

示例:

0 2 * * * /home/user/backup.sh

含义:每天凌晨 2:00 执行

3️⃣ 常见时间配置示例

需求 配置
每分钟 * * * * *
每 5 分钟 */5 * * * *
每小时 0 * * * *
每天 3:30 30 3 * * *
每周一 9 点 0 9 * * 1
每月 1 号 0 0 1 * *

4️⃣ 查看 / 删除

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

二、系统服务定时器:systemd timer(更现代)

1️⃣ 创建 service

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

内容:

[Unit]
Description=My Task

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

2️⃣ 创建 timer(控制时间)

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

示例(每天 4:00):

[Unit]
Description=Run mytask daily

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

[Install]
WantedBy=timers.target

3️⃣ 启用

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

4️⃣ 查看状态

systemctl list-timers

三、一次性定时:at

sudo apt install at
echo "sh /opt/test.sh" | at 23:30

如果你能说清楚:

  • 是 服务器定时脚本
  • 还是 桌面提醒
  • 还是 开机/间隔执行

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

0 踩