温馨提示×

debian定时器怎样设周期

小樊
40
2026-09-20 03:24:05
栏目: 智能运维

在 Debian(及大多数 Linux 发行版)里,“定时器”通常指 systemd timer。下面用最常见的方式说明如何设置周期


一、基本概念

systemd 定时器由两个文件组成:

  • .service:真正要执行的任务
  • .timer:定义什么时候执行(周期)

二、创建 Service 文件

例如:/etc/systemd/system/mytask.service

[Unit]
Description=My Task

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

三、创建 Timer 文件(核心:设置周期)

例如:/etc/systemd/system/mytask.timer

1️⃣ 固定周期(最常用)

[Unit]
Description=Run mytask every day

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

[Install]
WantedBy=timers.target

✅ 含义:每天凌晨 2 点执行


四、常见周期写法(OnCalendar)

需求 写法
每分钟 OnCalendar=*:0/1
每 5 分钟 OnCalendar=*:0/5
每小时 OnCalendar=hourly
每天 3 点 OnCalendar=*-*-* 03:00:00
每周一 4 点 OnCalendar=Mon *-*-* 04:00:00
每月 1 号 OnCalendar=*-*-01 00:00:00
每 30 秒 OnCalendar=*:*:0/30

五、使用时间间隔(非固定时间点)

[Timer]
OnActiveSec=10min
OnUnitActiveSec=1h
  • OnActiveSec:timer 启动后多久执行
  • OnUnitActiveSec:上次任务结束后多久再执行

⚠️ 这个方式不保证固定时间点


六、启用定时器

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

查看状态:

systemctl list-timers
systemctl status mytask.timer

七、调试技巧

journalctl -u mytask.service
journalctl -u mytask.timer

八、如果你说的是 cron(非 systemd)

Debian 也支持 cron:

crontab -e

示例(每天 2 点):

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

如果你能告诉我:

  • 想要 多久执行一次
  • systemd timer 还是 cron
  • Debian 版本(可选)

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

0