🕒 Cron 定时任务使用文档

cron 是 Linux 系统中用于周期性执行任务的守护进程。通过编写 crontab 文件,用户可以设定在特定时间自动运行脚本或命令。

📌 一、基本命令

命令 说明
crontab -e 编辑当前用户的定时任务
crontab -l 查看当前用户的定时任务
crontab -r 删除当前用户的定时任务
crontab -u [user] -e 编辑指定用户的定时任务(需 root 权限)

🧮 二、时间格式说明

cron 的时间格式由 5 个字段组成,后面跟要执行的命令:

* * * * * command_to_run
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ └─ 星期几 (0 - 7)(0 和 7 都表示星期天)
│ │ │ └──── 月份 (1 - 12)
│ │ └────── 一个月中的第几天 (1 - 31)
│ └──────── 小时 (0 - 23)
└────────── 分钟 (0 - 59)

🧪 三、示例任务

时间表达式 含义 示例命令
0 5 * * * 每天早上 5 点执行 0 5 * * * /home/user/backup.sh
*/10 * * * * 每 10 分钟执行一次 */10 * * * * /usr/bin/python3 /home/user/script.py
0 0 * * 0 每周日午夜执行 0 0 * * 0 /home/user/weekly_report.sh
30 8 1 * * 每月 1 日早上 8:30 执行 30 8 1 * * /home/user/monthly_task.sh

⚙️ 四、环境变量设置(可选)

crontab 文件顶部可以设置环境变量:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

确保你的脚本能在 cron 环境中找到所需命令。

📁 五、日志与调试

  • 默认日志路径:/var/log/cron 或使用 journalctl -u cron
  • 在命令后添加输出重定向以调试:
* * * * * /home/user/script.sh >> /home/user/cron.log 2>&1

🛡️ 六、注意事项

  • 脚本需有执行权限:chmod +x script.sh
  • 使用绝对路径,避免环境变量缺失导致任务失败
  • cron 不加载用户的 .bashrc.profile,需手动设置环境变量

案例:每小时检查某个服务状态

🧾 1. 创建检查脚本

首先,创建一个脚本文件,例如 /home/user/check_nginx.sh

#!/bin/bash

# 时间戳
timestamp=$(date '+%Y-%m-%d %H:%M:%S')

# 飞书 Webhook 地址
WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/你的Webhook地址"

# 检查 nginx 状态
if systemctl is-active --quiet nginx; then
    echo "$timestamp - nginx is running" >> /home/user/service_status.log
else
    echo "$timestamp - nginx is NOT running" >> /home/user/service_status.log

    # 构造 JSON 消息
    json=$(cat <<EOF
{
  "msg_type": "text",
  "content": {
    "text": "🚨 [$timestamp] nginx 服务异常,请检查!"
  }
}
EOF
)

    # 发送告警到飞书
    curl -X POST -H "Content-Type: application/json" -d "$json" "$WEBHOOK_URL"
fi

确保 curl 已安装

sudo apt install curl  # Debian/Ubuntu  
sudo yum install curl  # CentOS/RHEL

⏰ 3. 设置 Cron 定时任务

编辑 crontab

crontab -e

添加:

0 * * * * /home/user/check_nginx.sh

📋 4. 飞书告警效果

每当 nginx 服务异常时,你会在群里收到类似消息:

🚨 [2025-08-04 15:00:00] nginx 服务异常,请检查!
Copyright © https://yan-jian.com 2023 all right reserved更新时间: 2025-08-04 19:21:56

results matching ""

    No results matching ""