温馨提示×

怎样启用debian定时器

小樊
35
2026-10-04 20:11:54
栏目: 智能运维

在 Debian(以及大多数使用 systemd 的现代 Linux 发行版)中,“定时器”通常指 systemd timer(比传统的 cron 更灵活)。下面按从入门到常用的方式说明如何启用。


一、确认系统使用 systemd

systemctl --version

如果能看到版本信息,说明使用的是 systemd。


二、基本概念

systemd 定时器需要两个文件:

  1. Service 单元(要执行的任务)
  2. Timer 单元(何时执行)

三、示例:创建一个每天执行的定时器

1️⃣ 创建 Service 文件

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

内容示例:

[Unit]
Description=Hello Task

[Service]
Type=oneshot
ExecStart=/usr/bin/echo "Hello from systemd timer"

实际使用中可换成脚本路径,如 /opt/scripts/backup.sh


2️⃣ 创建 Timer 文件

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

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

[Unit]
Description=Run hello daily

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

[Install]
WantedBy=timers.target

常见时间写法:

  • OnCalendar=daily
  • OnCalendar=hourly
  • OnCalendar=Mon-Fri 09:00:00
  • OnBootSec=5min(开机 5 分钟后)

四、启用并启动定时器

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

五、查看定时器状态

systemctl list-timers
systemctl status hello.timer

查看下次执行时间:

systemctl list-timers hello.timer

六、手动测试

sudo systemctl start hello.service
journalctl -u hello.service

七、与传统 cron 的区别(可选)

特性 systemd timer cron
日志 journald /var/log
精度 高 中
依赖控制 强 弱
开机错过任务 支持 不支持

八、如果你指的是 cron(传统定时器)

crontab -e

示例(每天 3 点):

0 3 * * * /opt/scripts/backup.sh

如果你能告诉我:

  • 是想 替代 cron
  • 还是 开机/定时执行某个脚本
  • 或 系统版本(Debian 10/11/12)

我可以给你更精确的配置示例。

0 踩