温馨提示×

Debian定时器怎么配置

小樊
40
2026-08-26 04:03:16
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)里,定时器(Timer)通常是指 systemd Timer,用来替代传统的 cron。下面我按从简单到进阶给你讲清楚。


一、systemd Timer 是什么?

systemd Timer 用来定时触发 systemd 服务,比 cron 更强:

  • 支持开机后延迟执行
  • 支持日历式 / 单调时间
  • 日志由 journalctl 管理
  • 可精确到秒

二、基本概念

两个文件一组:

文件 作用
.service 定义要执行的任务
.timer 定义什么时候执行

三、示例:每分钟执行一次脚本

1️⃣ 创建脚本

sudo mkdir -p /usr/local/bin
sudo nano /usr/local/bin/mytask.sh

内容:

#!/bin/bash
echo "$(date) run" >> /tmp/mytask.log
sudo chmod +x /usr/local/bin/mytask.sh

2️⃣ 创建 service

sudo nano /etc/systemd/system/mytask.service
[Unit]
Description=My Task

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

3️⃣ 创建 timer

sudo nano /etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min

[Install]
WantedBy=timers.target

4️⃣ 启动并开机自启

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

5️⃣ 查看状态

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

四、常见时间配置方式

✅ 日历式(类似 cron)

OnCalendar=*-*-* *:*:00

示例:

需求 配置
每天 3 点 OnCalendar=03:00
每周一 8 点 OnCalendar=Mon *-*-* 08:00
每月 1 号 OnCalendar=*-*-01 00:00

✅ 单调时间(从某事件开始)

参数 含义
OnBootSec 开机后
OnActiveSec 启动后
OnUnitActiveSec 上次执行后

五、只运行一次(at 替代)

[Timer]
OnCalendar=2026-02-01 03:00
Persistent=true

六、与 cron 的区别

对比 cron systemd timer
精度 分钟
日志 邮件 journal
管理 crontab systemctl
依赖服务

七、常见问题

❓ timer 没生效?

systemctl daemon-reload
systemctl restart mytask.timer

❓ 查看所有 timer

systemctl list-timers --all

八、总结

Debian 定时器推荐用 systemd Timer
✅ 至少需要 .service + .timer
✅ 用 systemctl enable --now xxx.timer 启用


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

  • 你想 定时执行什么任务
  • 服务器 / 桌面
  • 是否需要 开机后延迟执行

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

0