在 Debian(以及大多数现代 Linux 发行版)中,“定时器”通常指的是 systemd 的 timer 单元,用来替代传统的 cron。下面我一步一步教你如何写和使用 Debian 的 systemd 定时器。
systemd 定时器由两个文件组成:
.service).timer)路径(推荐):
/etc/systemd/system/mytask.service
内容:
[Unit]
Description=My custom task
[Service]
Type=oneshot
ExecStart=/usr/local/bin/mytask.sh
⚠️
Type=oneshot表示任务执行一次就结束(定时器常用)
路径:
/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:00Persistent=true:如果系统关机错过时间,开机后补执行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=*: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
| 对比项 | systemd timer | cron |
|---|---|---|
| 日志 | journald | mail / 自定义 |
| 依赖管理 | 强 | 弱 |
| 精度 | 高 | 中 |
| 学习成本 | 略高 | 低 |
如果你愿意,我可以:
你打算用定时器做什么?