温馨提示×

debian定时器时间怎么设置

小樊
35
2026-10-16 13:10:40
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)中,“定时器”通常指 systemd 定时器(systemd timer) 或 cron 定时任务。下面分别说明。


一、使用 systemd 定时器(推荐,现代方式)

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 My Task

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target

3. 常见时间设置方式

  • 每天 02:30
    OnCalendar=*-*-* 02:30:00
    
  • 每小时
    OnCalendar=hourly
    
  • 每分钟
    OnCalendar=*-*-* *:*:00
    
  • 每周一 3 点
    OnCalendar=Mon *-*-* 03:00:00
    

4. 启用并启动

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

5. 查看状态

systemctl list-timers
systemctl status mytask.timer

二、使用 cron(传统方式)

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

crontab -e

2. 时间格式

分 时 日 月 周 命令

示例:

  • 每天 2:30 执行
    30 2 * * * /usr/local/bin/mytask.sh
    
  • 每 5 分钟执行
    */5 * * * * /usr/local/bin/mytask.sh
    
  • 每周一 3 点
    0 3 * * 1 /usr/local/bin/mytask.sh
    

3. 查看和日志

crontab -l

日志通常在:

journalctl -u cron
# 或
/var/log/syslog

三、如何选择?

  • 系统级、精确时间、可依赖启动状态 → systemd timer
  • 简单脚本、兼容性要求高 → cron

如果你能说下是 系统服务定时 还是 用户脚本定时,我可以给你更具体的示例。

0 踩