当前位置:首页>Linux>代码学习 | Linux | crontab 定时任务全套

代码学习 | Linux | crontab 定时任务全套

  • 2026-09-04 16:10:37
代码学习 | Linux | crontab 定时任务全套

输入一条 crontab 条目,定时任务就按计划自动执行——每晚备份结果目录、每月生成报告、每周清临时文件,把所有定期要跑的事交给 cron,自己只管写好脚本。cron 是 Linux 最老的调度系统,所有现代发行版预装,配置语法「分 时 日 月 周」五字段,记住了就全会了。最容易踩的坑是 cron 没有登录环境,PATH 只有 /usr/bin:/bin,conda/python 要用绝对路径或在脚本里 source ~/.bashrc。这一讲把 crontab 日常全套一次理清:查看/备份/恢复、时间字段语法、输出重定向、日志查看,以及 cron 环境变量问题的解决方案。


crontab 语法一图记住

crontab 每行一个任务,格式「m h dom mon dow command」——分、时、日、月、周、命令。加 >> 日志 2>&1 把 stdout/stderr 都写进文件,否则 cron 会发本地邮件,满了还占磁盘。

# 时间字段含义(分 时 日 月 周)
# * 表示每个,*/5 表示每隔5,1-5 表示范围
#
# 每分钟:    * * * * *  command
# 每小时整点:0 * * * *  command
# 每天凌晨2点:0 2 * * * command
# 每周日2点:  0 2 * * 0 command
# 每月1日0点:0 0 1 * *  command
# 每5分钟:   */5 * * * * command
# 工作日8点:  0 8 * * 1-5 command
#
# 日志重定向(推荐,防止发本地邮件):
# 0 2 * * * /home/user/backup.sh >> /home/user/logs/backup.log 2>&1

核心命令速查

按「查看/备份/服务 / 日志 / 系统 cron 目录 / 调试」分组:

#!/bin/bash
# crontab 定时任务命令速查 -- 按功能分组

# ---- 查看与备份 ----
crontab -l 2>/dev/null || echo "(当前无 cron 任务)"
crontab -l > ~/cron_backup.txt 2>/dev/null || true
cat ~/cron_backup.txt 2>/dev/null || echo "(备份为空)"
sudo crontab -u alice -l 2>/dev/null || true

# ---- 查看日志 ----
grep CRON /var/log/syslog 2>/dev/null | tail -10 || true
grep 'CRON.*CMD' /var/log/syslog 2>/dev/null | tail -5 || true
journalctl -u cron --since "today" -n 10 2>/dev/null || true
journalctl -u cron --since "1 hour ago" -n 20 2>/dev/null || true

# ---- 服务状态 ----
systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo "cron: unknown"
ps aux | grep -v grep | grep -i cron || true

# ---- 系统级 cron 目录 ----
ls /etc/cron.daily/
ls /etc/cron.hourly/ 2>/dev/null || true
ls /etc/cron.weekly/ 2>/dev/null || true
ls /etc/cron.d/ 2>/dev/null || true
cat /etc/crontab

# ---- 脚本调试 ----
bash -n testdata/backup_demo.sh

crontab -l 2>/dev/null || echo ... 安全列出(没有任务时不报错);bash -n script.sh 只检查语法不执行,写好脚本先这样验证。

示例的输出日志

只跑只读命令验证:cron 服务状态、系统 cron 目录、脚本语法检查:

=== crontab 当前任务 ===
# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
# 微信公众号文献自动推送 - 每30分钟检索邮箱
3 6 * * * ~/.claude/skills/sci-explorer/scripts/daily_runner.sh >> ~/.claude/skills/sci-explorer/logs/cron_$(date +\%Y\%m\%d).log 2>&1
0 6 * * 5 ~
30 6 * * * ~/.claude/skills/lawyer-daily-script/run_daily.sh
*/30 * * * * ~/.larkclaw/summarize_half_hour.sh >> ~/.larkclaw/cron.log 2>&1
*/30 * * * * ~ >> ~ 2>&1
20 6 * * * ~/.mimocode/config/skill/finance-daily/run_daily.sh >> ~/.mimocode/config/skill/finance-daily/logs/cron_$(date +\%Y\%m\%d).log 2>&1
0 14 * * 5 ~/.claude/skills/wechat-code/cron_weekly.sh >> ~ 2>&1
# 肿瘤热点论文月度量化排名 (wechat-onco-hot) — 每天守卫,本月未跑则补跑
0 8 * * * ~

=== cron 服务状态 ===
active

=== 系统定时目录 ===
0anacron
apport
apt-compat
dpkg
google-chrome
logrotate
man-db
plocate

=== /etc/crontab 前 10 行 ===
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
# You can also override PATH, but by default, newer versions inh

backup_demo.sh 语法正确、/etc/cron.daily 目录存在——说明系统 cron 正常,模板脚本可以直接改路径用于真实备份任务。

扩展:cron 脚本与注意事项

cron 没有登录环境,这几点必须注意才能让任务真正跑起来:

# 方法1:脚本里手动加载环境
source ~/.bashrc          # bash 脚本开头加这一行
conda activate omic       # 再激活环境

# 方法2:在 crontab 里指定 PATH
SHELL=/bin/bash
PATH=/opt/conda/bin:/usr/local/bin:/usr/bin:/bin
MAILTO=""                 # 不发本地邮件

# 方法3:用绝对路径调用命令
/opt/conda/envs/omic/bin/python3 /home/user/code/run.py

# 修改/删除 crontab(危险,谨慎执行)
EDITOR=nano crontab -e          # 打开编辑器编辑
crontab -r                      # 删除当前用户全部 cron(不可撤销)
echo "0 2 * * * /path/to/backup.sh >> ~/logs/backup.log 2>&1" | crontab -  # 非交互添加
crontab -l

crontab -r 会删掉所有 cron 任务,操作前先 crontab -l > ~/backup.txt 备份;cron 脚本里的相对路径以 / 为起点,记得用绝对路径。

避坑指南

  • 任务没执行 → 先查 grep CRON /var/log/syslog | tail -20 看 cron 日志;确认 cron 服务在跑
  • 手动跑 OK,cron 里失败 → cron 没有 conda/PATH,脚本首行加 source ~/.bashrc
  • 一直发本地邮件 → crontab 加 MAILTO="" 或重定向 >> log.txt 2>&1
  • 时间字段搞错 → crontab -l 贴到 crontab.guru 网站验证语法

📦 完整代码 + 测试数据下载
百度网盘链接:https://pan.baidu.com/s/1XwB1dIDLpsVpSGGWzwktOQ?pwd=l22c
提取码:l22c(代码已实测可直接运行,建议保存到自己网盘)

最新文章

随机文章