温馨提示×

怎样创建debian定时器

小樊
51
2026-09-23 02:57:10
栏目: 智能运维

在 Debian(以及其它使用 systemd 的 Linux 发行版)中,创建“定时器”通常是指使用 systemd timer(相当于传统 cron 的现代替代方案)。下面我分步骤说明如何创建一个 Debian 定时器。


一、基本概念

systemd 定时器由两个部分组成:

  1. Service 单元(.service)
    定义“要执行什么任务”
  2. Timer 单元(.timer)
    定义“什么时候执行”

二、示例:每天执行一次脚本

1️⃣ 创建 Service 文件

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

内容示例:

[Unit]
Description=My custom task

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

Type=oneshot 表示任务执行完就结束(适合脚本)

确保你的脚本可执行:

sudo chmod +x /usr/local/bin/myscript.sh

2️⃣ 创建 Timer 文件

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

内容示例(每天 03:00 执行):

[Unit]
Description=Run mytask daily

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

[Install]
WantedBy=timers.target

常用时间写法:

  • OnCalendar=daily → 每天
  • OnCalendar=hourly → 每小时
  • OnCalendar=weekly → 每周
  • OnCalendar=*-*-* 03:00:00 → 指定时间

3️⃣ 启用并启动定时器

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

4️⃣ 查看定时器状态

systemctl list-timers
systemctl status mytask.timer

三、手动测试 Service

sudo systemctl start mytask.service

四、与 cron 的对比(简要)

特性 systemd timer cron
日志 journalctl 邮件/文件
精度 高 中
依赖管理 强 弱
现代系统推荐 ✅ ⚠️

五、常见错误排查

  • ❌ 脚本无执行权限
  • ❌ Service 没写 Type=oneshot
  • ❌ 忘了 systemctl daemon-reload
  • ❌ Timer 没 enable

如果你有具体需求(例如:开机延迟执行、每 5 分钟、只在工作日),可以告诉我,我可以帮你写完整的 .timer 配置。

0 踩