温馨提示×

debian定时器怎么启用

小樊
38
2026-09-01 21:15:38
栏目: 智能运维

在 Debian 里“定时器”通常指 systemd timer(现代 Debian 默认用 systemd)。下面按最常见场景说明如何启用并运行一个 timer


一、确认系统使用 systemd

ps -p 1 -o comm=

输出是 systemd 就没问题。


二、启用一个已有的 systemd timer

假设你有一个 timer 单元:mytask.timer

1. 重新加载 systemd(可选,新建/修改后执行)

sudo systemctl daemon-reload

2. 启用(开机自启)

sudo systemctl enable mytask.timer

3. 立即启动

sudo systemctl start mytask.timer

4. 查看状态

systemctl status mytask.timer

5. 查看下次执行时间

systemctl list-timers mytask.timer

三、示例:创建一个简单定时器

1. 创建 service(真正干活的)

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

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

2. 创建 timer(定时触发)

# /etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

3. 启用并启动

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

四、如果是“旧式” cron(非 systemd timer)

Debian 也支持 cron:

sudo systemctl enable cron
sudo systemctl start cron

编辑定时任务:

crontab -e

示例(每天 3 点):

0 3 * * * /usr/local/bin/mytask.sh

五、常见问题

  • 只 start 不 enable:重启后不会自动运行
  • timer 不触发:检查 OnCalendar 是否写错
  • 查看日志
journalctl -u mytask.timer
journalctl -u mytask.service

如果你有具体的 timer 名称或需求(如每隔 10 分钟 / 开机后延迟),我可以帮你写完整配置。

0