侧边栏壁纸
博主头像
faneok博主等级

重剑无锋,大巧不工

  • 累计撰写 33 篇文章
  • 累计创建 17 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Linux中定时任务

faneok
2025-05-21 / 0 评论 / 0 点赞 / 31 阅读 / 4261 字

在 Linux 系统中,定时任务主要通过 ​cron​​ 服务实现,它允许用户按计划自动执行命令或脚本


​1. cron 基础​

  • ​服务管理​​:

    # 检查 cron 是否运行(通常系统默认启动)
    systemctl status cron   # Debian/Ubuntu
    systemctl status crond  # CentOS/RHEL
    
    # 启动/重启/停止服务
    sudo systemctl start cron
  • ​日志查看​​:

    sudo tail -f /var/log/syslog | grep cron   # Debian/Ubuntu
    sudo journalctl -u crond -f                # CentOS/RHEL
  • 强制重新加载 Cron 配置​​

    如果修改了 /etc/crontab 或 /etc/cron.d/ 下的任务,可以重新加载 cron 服务:

    sudo systemctl restart cron   # Debian/Ubuntu
    sudo systemctl restart crond  # CentOS/RHEL

​2. 编辑用户级定时任务​

  • ​命令​​:

    crontab -e  # 编辑当前用户的定时任务
  • ​文件格式​​:

    * * * * * command_to_execute
    │ │ │ │ │
    │ │ │ │ └── 星期 (0-7, 0和7均为周日)
    │ │ │ └──── 月份 (1-12)
    │ │ └────── 日 (1-31)
    │ └──────── 小时 (0-23)
    └────────── 分钟 (0-59)
  • ​示例​​:

    0 3 * * * /path/to/backup.sh    # 每天凌晨3点执行
    */15 * * * * /usr/bin/date      # 每15分钟输出当前时间
    @reboot /path/to/startup.sh     # 系统启动时执行(非标准cron语法,部分系统支持)

​3. 系统级定时任务​

  • ​配置文件路径​​:

    • /etc/crontab:需指定用户身份,格式为:

      0 1 * * * root /path/to/system_script.sh
    • /etc/cron.d/:可放置独立的任务文件,格式同/etc/crontab

  • ​限制访问​​:

    • 通过 /etc/cron.allow/etc/cron.deny 控制用户权限。


​4. 特殊快捷语法​

  • crontab -e 中可使用别名(部分系统支持):

    @daily     /path/to/daily_job.sh   # 每天午夜执行
    @hourly    /path/to/hourly_task    # 每小时
    @weekly    /path/to/weekly_cleanup # 每周日午夜
    @monthly   /path/to/monthly_report  # 每月1日午夜

​5. 环境变量问题​

  • cron 默认环境与用户登录环境不同,建议:

    • 在脚本中设置绝对路径。

    • 或在 crontab 中声明变量:

      PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
      0 * * * * /path/to/script.sh > /tmp/log 2>&1

​6. 调试技巧​

  • ​手动测试命令​​:

    /path/to/script.sh
  • ​记录输出​​:

    * * * * * /path/to/script.sh >> /tmp/cron.log 2>&1
  • ​检查执行权限​​:

    chmod +x /path/to/script.sh

​7. 替代工具:at​​

  • 单次任务调度:

    echo "rm /tmp/*.tmp" | at 10:00 PM   # 今晚10点执行
    atq                                  # 查看待执行任务

0

评论区