温馨提示×

debian定时器如何配置周期

小樊
45
2026-10-25 09:30:34
栏目: 智能运维

在 Debian(以及其他使用 systemd 的现代 Linux 发行版)中,定时任务推荐用 systemd timer(取代传统的 cron)。下面按“周期配置”详细讲清楚。


一、systemd Timer 基本组成

一个定时任务通常由两个文件组成:

  1. service 文件:定义“要执行什么”
  2. timer 文件:定义“什么时候执行”

路径一般放在:

/etc/systemd/system/

二、示例:每天凌晨执行脚本

1️⃣ 创建 service 文件

/etc/systemd/system/mytask.service

[Unit]
Description=My scheduled task

[Service]
Type=oneshot
ExecStart=/usr/local/bin/myscript.sh

2️⃣ 创建 timer 文件

/etc/systemd/system/mytask.timer

[Unit]
Description=Run mytask daily

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

[Install]
WantedBy=timers.target

3️⃣ 启用并启动

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

查看状态:

systemctl list-timers

三、周期配置(OnCalendar 语法)

OnCalendar 是最常用的周期配置方式。

常见示例

需求 配置
每分钟 *-*-* *:*:00
每小时 *-*-* *:00:00
每天 3 点 *-*-* 03:00:00
每周一 9 点 Mon *-*-* 09:00:00
每月 1 号 *-*-01 00:00:00
每年 1 月 1 日 *-01-01 00:00:00

✅ 支持星期缩写:Mon Tue Wed Thu Fri Sat Sun


四、更灵活的周期方式

1️⃣ 固定间隔(不关心具体时间)

[Timer]
OnUnitActiveSec=1h

含义:

  • 上一次执行后 1 小时再执行
  • 适合“每隔 X 时间”

常用单位:

  • sec
  • min
  • h
  • day
  • week

示例:

OnUnitActiveSec=30min
OnBootSec=5min

2️⃣ 开机后延迟执行

OnBootSec=10min

3️⃣ 随机延迟(避免集中触发)

RandomizedDelaySec=300

五、Persistent 的作用

Persistent=true
  • 如果系统关机时该执行的时间错过了
  • 开机后会补执行一次

❌ 不写或 false:错过就错过


六、查看与调试

# 查看所有定时器
systemctl list-timers

# 查看某个 timer
systemctl status mytask.timer

# 手动触发
systemctl start mytask.service

# 查看日志
journalctl -u mytask.service

七、传统方式(cron,不推荐但可用)

如果你只是想快速用:

crontab -e

示例(每天 2 点):

0 2 * * * /usr/local/bin/myscript.sh

⚠️ cron 不适合系统服务级任务,也不支持开机补执行。


八、总结建议

✅ 推荐:

  • 系统任务 → systemd timer
  • 需要周期 / 稳定 / 日志 / 可控

✅ 简单脚本:

  • cron 也可以

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

  • 执行频率(每分钟 / 每小时 / 每周)
  • 是否需开机补跑
  • 是否是服务器任务

我可以直接帮你写完整配置。

0 踩