定时任务默认不生效 limits.conf,需通过 limits.d 显式配置用户限制、脚本中 ulimit 设置、调大 fs.file-max 内核参数,或 systemd 服务中设 LimitNOFILE。

定时任务(如 cron 作业)默认不经过 PAM 登录流程,因此 /etc/security/limits.conf 中的配置通常对其**不生效**。要让定时任务运行的进程拥有足够文件句柄数,关键在于确保其**启动环境能继承或显式应用句柄限制**。以下是针对 /etc/security/limits.d/ 及相关机制的有效配置方式:
确认定时任务实际运行用户并为其单独配置
/etc/security/limits.d/ 下的配置文件按字母顺序加载,会覆盖 /etc/security/limits.conf 中同 domain 的设置。它对 cron 启动的 shell 进程仍有限制——前提是该用户通过 PAM 登录过(例如 root 或普通用户曾 ssh 登录),且 cron 使用了 pam_limits 模块(多数麒麟、CentOS 7+ 默认启用)。
- 为 cron 常用用户(如
root或具体应用用户appuser)创建专属配置文件:sudo vim /etc/security/limits.d/90-cron-nofile.conf - 写入明确的软硬限制(soft 必须 ≤ hard):
root soft nofile 65536root hard nofile 65536appuser soft nofile 65536appuser hard nofile 65536 - 避免使用
*通配符替代 root:root 用户的限制不会被*覆盖,必须显式声明
在定时任务脚本中主动调用 ulimit
这是最可靠、不依赖 PAM 和登录会话的方式。cron 执行时直接在 shell 环境中设限:
- 编辑 crontab(
crontab -e)或系统级定时任务(/etc/crontab)时,在命令前加ulimit -n 65536 &&:* * * * * ulimit -n 65536 && /path/to/your/script.sh - 更规范的做法是在脚本头部加入:
#!/bin/bash<br> ulimit -n 65536 || { echo "Failed to set nofile limit"; exit 1; } - 注意:普通用户只能将 soft nofile 提升至其 hard 限制值;若 hard 未设够,需先完成上一步配置
确保系统级总上限支撑用户级限制
即使用户级设为 65536,若内核总句柄池不足(fs.file-max 过小),所有限制都形同虚设:
- 检查当前值:
cat /proc/sys/fs/file-max - 永久提升(推荐 ≥ 2097152):
在/etc/sysctl.conf中添加:fs.file-max = 2097152
然后执行sudo sysctl -p - 验证是否足够:
echo $(cat /proc/sys/fs/file-nr | awk '{print $3}') > /proc/sys/fs/file-max可临时测试,但生产环境务必走永久配置
对 systemd 定时器(.timer)必须单独处理
若使用 systemd-run --on-calendar 或自定义 .timer 单元,其完全绕过 limits.d,必须在 service 单元中声明:
- 编辑对应服务单元(如
myjob.service):sudo systemctl edit --full myjob.service - 在
[Service]段添加:LimitNOFILE=65536 - 重载并重启:
sudo systemctl daemon-reload && sudo systemctl restart myjob.service

















