温馨提示×

怎样写debian定时器

小樊
35
2026-10-07 17:54:14
栏目: 智能运维

在 Debian(以及大多数现代 Linux 发行版)中,“定时器”通常指的是 systemd 的 timer 单元,用来替代传统的 cron。下面我一步一步教你如何写和使用 Debian 的 systemd 定时器。


一、基本概念

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

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

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

1️⃣ 创建 Service 文件

路径(推荐):

/etc/systemd/system/mytask.service

内容:

[Unit]
Description=My custom task

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

⚠️ Type=oneshot 表示任务执行一次就结束(定时器常用)


2️⃣ 创建 Timer 文件

路径:

/etc/systemd/system/mytask.timer

内容:

[Unit]
Description=Run mytask daily

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

[Install]
WantedBy=timers.target

说明:

  • OnCalendar=*-*-* 02:00:00:每天 2:00
  • Persistent=true:如果系统关机错过时间,开机后补执行

3️⃣ 创建你的脚本

sudo nano /usr/local/bin/mytask.sh

内容示例:

#!/bin/bash
echo "$(date) task run" >> /var/log/mytask.log

赋予执行权限:

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

三、启用并启动定时器

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

查看状态:

systemctl status mytask.timer

查看所有定时器:

systemctl list-timers

四、常用 OnCalendar 写法

需求 写法
每分钟 OnCalendar=*:0/1
每小时 OnCalendar=hourly
每天 3:30 OnCalendar=*-*-* 03:30:00
每周一 9 点 OnCalendar=Mon *-*-* 09:00:00
每月 1 号 OnCalendar=*-*-01 00:00:00
开机 10 分钟后 OnBootSec=10min

五、调试技巧

手动执行 service:

sudo systemctl start mytask.service

查看日志:

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

六、和 cron 的区别(简单对比)

对比项 systemd timer cron
日志 journald mail / 自定义
依赖管理 强 弱
精度 高 中
学习成本 略高 低

如果你愿意,我可以:

  • 给你写一个 开机延迟执行 的定时器
  • 帮你把 cron 任务改成 systemd
  • 写一个 失败自动重试 的 timer

你打算用定时器做什么?

0 踩