温馨提示×

debian定时器如何定时任务

小樊
46
2026-10-04 20:10:55
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)中,“定时任务”通常有两种主流方式:

  1. cron / crontab(传统、最常用)
  2. systemd timer(新一代,更强大,适合系统级任务)

下面分别说明。


一、使用 crontab(推荐入门)

1. 编辑当前用户的定时任务

crontab -e

2. 基本格式

* * * * *  command
│ │ │ │ │
│ │ │ │ └─ 星期 (0-7,0和7都是周日)
│ │ │ └─── 月份 (1-12)
│ │ └───── 日期 (1-31)
│ └─────── 小时 (0-23)
└───────── 分钟 (0-59)

3. 常见示例

# 每天凌晨 3 点执行
0 3 * * * /home/user/backup.sh

# 每 5 分钟执行一次
*/5 * * * * /usr/bin/python3 /home/user/task.py

# 每周一 9:30
30 9 * * 1 /home/user/weekly.sh

4. 查看 / 删除

crontab -l      # 查看
crontab -r      # 删除全部

系统级任务可放在:/etc/crontab 或 /etc/cron.d/


二、使用 systemd timer(更现代)

适合系统服务、精确控制、日志记录。

示例:每天执行脚本

1. 创建 service

sudo vim /etc/systemd/system/mytask.service

内容:

[Unit]
Description=My Task

[Service]
Type=oneshot
ExecStart=/home/user/mytask.sh

2. 创建 timer

sudo vim /etc/systemd/system/mytask.timer

内容:

[Unit]
Description=Run My Task Daily

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

3. 启用并启动

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

4. 查看状态

systemctl list-timers

三、如何选择?

场景 推荐
简单脚本、个人任务 crontab
系统服务、需要日志 systemd timer
需要秒级控制 systemd timer

四、排错建议

  • cron 任务加日志:
* * * * * /script.sh >> /var/log/script.log 2>&1
  • 检查 cron 是否运行:
systemctl status cron

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

  • 你是 用户级还是系统级
  • 想 多久执行一次
  • 执行的 是什么命令/脚本

我可以直接帮你写配置。

0 踩