使用shell脚本编写程序定时查询数据库,根据数据库结果发送短信和邮件。定时任务使用crontab实现,具体实现如下。
1. crontab 定时执行任务
crontab -e进行编辑,使用方法类似于vi,
例子:0 * * * * bash /home/work/opt/nginx/sbin/nginx_log.sh
2. 完整脚本
#!/bin/bash
if [ $# -lt 2 ]
then
echo "params error";
exit;
fi
#创建日志文件
LOG_FILE_NAME="/home/work/monitor/xxx"$1".log"
if [ ! -e "$LOG_FILE_NAME" ]
then
touch $LOG_FILE_NAME;
fi
LOG=$(date "+%Y-%m-%d %H:%M:%S");
#当前时间
current_time=$(date +%s);
echo $current_time
#查询开始时间
start_time=$(($current_time-$3))
echo $start_time;
tag=${1}
query_total_num_sql="select count(1) from unionsdkmonitor where tag like '%${tag}%' and timestamp>='${start_time}' and timestamp<='${current_time}'"
total_num=$(/usr/bin/mysql -h10.11.0.90 -P4051 -uuser -ppassword -N gamesdkmonitor -s -e "${query_total_num_sql}");
echo ${total_num};
error_result="0";
query_error_num_sql="select count(1) from unionsdkmonitor where tag like '%${tag}%' and timestamp>='${start_time}' and timestamp<='${current_time}' and result=${error_result}";
error_num=$(/usr/bin/mysql -h10.11.0.90 -P4051 -uuser -ppassword -N gamesdkmonitor -s -e "${query_error_num_sql}");
echo ${error_num}
#总条数小于5条不报警。
if [ 5 -gt ${total_num} ]
then
exit;
fi
error_per=$[error_num*100/total_num];
time=$[$3/60];
LOG=${LOG}" "$2" totalnum="${total_num}" error_num="${error_num}" error_per="${error_per}"%";
#记录日志
echo $LOG >> $LOG_FILE_NAME
#大于阀值,发送短信和邮件
echo $error_per
if [ $error_per -gt 50 ]
then
message="$2接口过去$time分钟访问$total_num次,失败$error_num次,错误率为百分之$error_per,时间"$(date "+%Y-%m-%d %H:%M:%S")".";
#xxx
phones=(xxxx xxxx)
#phones=(15011549635)
for var1 in ${phones[@]}
do
#发送短信
curl "http://ip/message.php?phone=$var1&message=$message"
done
#发送邮件
/home/liuqi/sendEmail -t [email protected],[email protected] -f [email protected] -s smtp.qiye.163.com:25 -xu [email protected] -xp Lv6bYuMW8a -m $message -u "标题"
echo $message;
fi
exit;