温馨提示×

debian定时器如何写单元文件

小樊
47
2026-09-14 00:26:57
栏目: 智能运维

在 Debian(以及其它使用 systemd 的 Linux 发行版)中,定时任务通常通过 systemd timer + service 单元文件 来实现,相当于“加强版 crontab”。

下面一步步说明如何写单元文件。


一、基本组成

一个 systemd 定时任务通常有两个文件:

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

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

1️⃣ 编写 service 文件

路径(推荐):

/etc/systemd/system/mytask.service

内容:

[Unit]
Description=My scheduled task

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

✅ Type=oneshot 表示任务执行一次就结束
✅ ExecStart 必须是绝对路径


2️⃣ 编写 timer 文件

路径:

/etc/systemd/system/mytask.timer

内容:

[Unit]
Description=Run mytask daily

[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
Unit=mytask.service

[Install]
WantedBy=timers.target

说明:

  • OnCalendar=*-*-* 00:00:00:每天 0 点
  • Persistent=true:如果系统关机错过时间,开机后补执行
  • Unit=:指定要运行的 service(默认同名可不写)

三、常用时间写法(OnCalendar)

需求 写法
每天 3 点 *-*-* 03:00:00
每周一 9 点 Mon *-*-* 09:00:00
每月 1 号 *-*-01 00:00:00
每 10 分钟 *:0/10:00
每小时 hourly
每天 daily

也支持:

OnBootSec=5min
OnUnitActiveSec=1h

四、启动与启用

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

五、查看状态

systemctl status mytask.timer
systemctl list-timers
journalctl -u mytask.service

六、对比 crontab 的优势

✅ 可记录日志(journalctl)
✅ 支持依赖、失败重试
✅ 更精确的时间控制
✅ 系统级 / 用户级都支持


如果你有具体需求(比如“每 5 分钟”、“开机后延迟执行”、“用户级 timer”),可以告诉我,我可以直接帮你写完整文件。

0 踩