一、说明
使用jcmd和lsof命令监控程序线程异常占用情况,在Crontab增加了定时任务,每半小时输出一次内容。设置定时任务后,发现jcmd内容可正常输出,lsof只生成文件不输出内容,但手动执行脚本可以输出内容。
#!/bin/bash
jarpid=`jps -l|grep jar包|grep -v 'grep'|awk '{print $1}'`
time=`date "+%Y-%m-%d %H:%M:%S"`
jcmd ${jarpid} Thread.print -l >> jar包路径/jcmd_${time}.txt
lsof -p ${jarpid} >> jar包路径/lsof_${time}.txt
二、解决办法
crontab有一个问题,就是它不会从profile文件中读取环境变量参数,经常导致在手工执行某个脚本时是成功的,但是到crontab中试图让它定期执行时就是会出错。
所以原因就在于,crontab没有去读环境变量,需要再脚本中手动引入环境变量。
在脚本中加入了引入环境变量的配置:
#!/bin/bash
source /etc/profile
source ~/.bash_profile
jarpid=`jps -l|grep jar包|grep -v 'grep'|awk '{print $1}'`
time=`date "+%Y-%m-%d %H:%M:%S"`
jcmd ${jarpid} Thread.print -l >> jar包路径/jcmd_${time}.txt
lsof -p ${jarpid} >> jar包路径/lsof_${time}.txt
问题解决!