温馨提示×

怎样设置debian定时器周期

小樊
47
2026-10-19 11:57:44
栏目: 智能运维

在 Debian 中,“定时器周期”通常指 systemd timer(推荐方式)或 cron。下面分别说明。


一、使用 systemd timer(Debian 推荐)

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:

固定周期(如每 10 分钟)

[Unit]
Description=Run mytask every 10 minutes

[Timer]
OnCalendar=*:0/10
Persistent=true

[Install]
WantedBy=timers.target

每天凌晨 3 点

OnCalendar=03:00

每小时

OnCalendar=hourly

每周一 4 点

OnCalendar=Mon 04:00

3. 启用并启动

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

4. 查看状态

systemctl list-timers
systemctl status mytask.timer

二、使用 cron(传统方式)

编辑当前用户 cron:

crontab -e

示例:

# 每 10 分钟
*/10 * * * * /usr/local/bin/mytask.sh

# 每天 3 点
0 3 * * * /usr/local/bin/mytask.sh

# 每周一 4 点
0 4 * * 1 /usr/local/bin/mytask.sh

系统级 cron:

/etc/cron.d/
/etc/cron.daily/
/etc/cron.hourly/

三、常见周期写法对照

需求 systemd cron
每 5 分钟 OnCalendar=*:0/5 */5 * * * *
每小时 OnCalendar=hourly 0 * * * *
每天 OnCalendar=daily 0 0 * * *
每周 OnCalendar=weekly 0 0 * * 0

如果你有 具体周期需求(如“每 2 小时”“工作日 9–18 点”),可以告诉我,我帮你写完整配置。

0 踩