You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux共享主机Node.js进程异常:如何用Cron任务终止闲置进程?

解决Cron定时终止闲置1小时的Node.js进程问题

实现步骤

1. 编写清理脚本

创建名为clean_idle_node.sh的Shell脚本,内容如下:

#!/bin/bash
# 终止运行时长超过1小时的Node.js进程
ps -eo pid,cmd,etimes | grep -i node | grep -v grep | while read pid cmd etimes; do
    # etimes为进程已运行秒数,3600秒=1小时
    if [ $etimes -ge 3600 ]; then
        kill -9 $pid
    fi
done

若主机不支持etimes字段,改用解析etime格式的版本:

#!/bin/bash
ps -eo pid,cmd,etime | grep -i node | grep -v grep | while read pid cmd etime; do
    total_seconds=0
    # 拆分天数与时分秒
    if [[ $etime == *-* ]]; then
        days=${etime%-*}
        time_part=${etime#*-}
        total_seconds=$((days*86400))
    else
        time_part=$etime
    fi
    # 转换时分秒为总秒数
    IFS=':' read -r h m s <<< "$time_part"
    total_seconds=$((total_seconds + h*3600 + m*60 + s))
    if [ $total_seconds -ge 3600 ]; then
        kill -9 $pid
    fi
done

2. 设置脚本执行权限

通过主机文件管理器右键脚本,勾选执行权限;若支持命令行则执行:

chmod +x clean_idle_node.sh

3. 添加Cron定时任务

在主机面板的Cron管理界面,添加定时规则(示例为每小时执行一次):

0 * * * * /home/你的用户名/clean_idle_node.sh

注意替换脚本的实际存放路径。

额外排查技巧

  • 若kill -9权限不足,尝试用kill -TERM $pid优雅终止进程
  • 可在脚本中添加日志输出,方便定位问题:
    LOG_FILE="/home/你的用户名/node_cleanup.log"
    echo "[$(date)] 开始清理进程..." >> $LOG_FILE
    # 在kill后添加日志
    kill -9 $pid && echo "[$(date)] 终止进程PID: $pid (运行时长: $etimes 秒)" >> $LOG_FILE
    

内容的提问来源于stack exchange,提问作者Gourav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 17:27:33