分类: crontab

  • cronshell 多台服务器相同 crontab 只执行一次

    https://github.com/selboo/cronshell

    cronshell

    多台服务器相同 crontab 只执行一次

    cronshell 安装

    # go build
    

    cronshell 配置

     # cat /etc/cronshell.conf
    [Log]
    logfile=/var/log/cronshell.log
    
    [Redis]
    host=192.168.15.100
    port=6379
    
    • logfile 日志路径
    • host redis 地址
    • port redis 端口

    crontab 配置

    服务器 Server A01

    # cat /etc/cron.d/cronshell
    MAILTO=""
    SHELL=/bin/cronshell
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    
    * * * * * root d=$(date); echo $d run ok >> /tmp/t.log
    

    查看执行结果

    # cat /tmp/t.log
    Sat May 30 22:47:01 CST 2020 run ok
    Sat May 30 22:48:01 CST 2020 run ok
    Sat May 30 22:51:01 CST 2020 run ok
    Sat May 30 22:54:01 CST 2020 run ok
    

    服务器 Server B01

    # cat /etc/cron.d/cronshell
    MAILTO=""
    SHELL=/bin/cronshell
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    
    * * * * * root d=$(date); echo $d run ok >> /tmp/t.log
    

    查看执行结果

    # cat /tmp/t.log
    Sat May 30 22:49:01 CST 2020 run ok
    Sat May 30 22:50:01 CST 2020 run ok
    Sat May 30 22:52:01 CST 2020 run ok
    Sat May 30 22:53:01 CST 2020 run ok
    Sat May 30 22:55:01 CST 2020 run ok
    Sat May 30 22:56:01 CST 2020 run ok
    

    转载请注明:爱开源 » cronshell 多台服务器相同 crontab 只执行一次

  • crontab为何自动中断

    在最近开发的一个系统中,有一个定时任务,每天需要将一份数据(大约200w条),发送至一个线上key-value存储系统中。

    说到定时任务,最常见的,就是使用crontab。原来这一套系统已经开发完成,部署在深圳IDC,工作良好。最近,需要在天津IDC也部署一套。但是在天津部署之后,我却发现,天津的这套系统每天只能定时发送48999条数据(准确数字),然后就自动停止了。

    我首先尝试了crontab -l,并直接手动执行其输出中的相关脚本。这时可以发现,程序并没有中断,完整发送了所有数据。

    这时我一度怀疑,是我在程序中设置了什么阈值,才能导致每天都无比准确的发送48999条数据就停止。但是复查一遍代码后并没有查询到什么可疑的配置。

    接下来我又在网上搜索crontab相关的问题,但是大都是写一些无法启动crontab相关脚本的问题,对于我这种程序可以定时启动,但是又“准确”的自动中断的问题,却没什么相关答案。

    考虑到在深圳IDC没有问题,但是在天津IDC却出现了这个诡异的问题。两个IDC使用的机器型号并不一致,于是我又从机器的角度重新查找crontab相关的问题,终于找到的罪魁祸首:

    原来,这是由于在部分机器上,crontab对于执行程序的输出有大小限制,输出超出一定的字节之后就会自动停止程序。

    而我的程序每发送1000条数据即会输出一条log,所以每次正好输出49000这条log之后,就超出了大小限制,因此每次都会自动停止在48999条了。

    解决方案:可以 重定向输出至 >/dev/null,如:

    1 8 * * * cd /path/to/your/bin/ && ./your_bin –flagfile=../conf/your.flags >/dev/null 2>&1 &

    希望遇到类似问题的同学,可以尽快的搜索到我这篇文章。

    转载请注明:爱开源 » crontab为何自动中断

  • python实现的解析crontab配置文件代码

    这篇文章主要介绍了 实现的解析 配置文件代码,也可以说是 版的 代码中包含大量注释,需要的朋友可以参考下

    #/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    """
    1.解析 crontab 配置文件中的五个数间参数(分 时 日 月 周),获取他们对应的取值范围
    2.将时间戳与crontab配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
    """
    
    #$Id $
    
    import re, time, sys
    from Core.FDateTime.FDateTime import FDateTime
    
    def get_struct_time(time_stamp_int):
        """
        按整型时间戳获取格式化时间 分 时 日 月 周
        Args:
            time_stamp_int 为传入的值为时间戳(整形),如:1332888820
            经过localtime转换后变成
            time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
        Return:
            list____返回 分 时 日 月 周
        """
    
        st_time = time.localtime(time_stamp_int)
        return [st_time.tm_min, st_time.tm_hour, st_time.tm_mday, st_time.tm_mon, st_time.tm_wday]
    
    def get_strptime(time_str, str_format):
        """从字符串获取 整型时间戳
        Args:
            time_str 字符串类型的时间戳 如 '31/Jul/2013:17:46:01'
            str_format 指定 time_str 的格式 如 '%d/%b/%Y:%H:%M:%S'
        Return:
            返回10位整型(int)时间戳,如 1375146861
        """
        return int(time.mktime(time.strptime(time_str, str_format)))
    
    def get_str_time(time_stamp, str_format='%Y%m%d%H%M'):
        """
        获取时间戳,
        Args:
            time_stamp 10位整型(int)时间戳,如 1375146861
            str_format 指定返回格式,值类型为 字符串 str
        Rturn:
            返回格式 默认为 年月日时分,如2013年7月9日1时3分 :201207090103
        """
        return time.strftime("%s" % str_format, time.localtime(time_stamp))
    
    def match_cont(patten, cont):
        """
        正则匹配(精确符合的匹配)
        Args:
            patten 正则表达式
            cont____ 匹配内容
        Return:
            True or False
        """
        res = re.match(patten, cont)
        if res:
            return True
        else:
            return False
    
    def handle_num(val, ranges=(0, 100), res=list()):
        """处理纯数字"""
        val = int(val)
        if val >= ranges[0] and val <= ranges[1]:
            res.append(val)
        return res
    
    def handle_nlist(val, ranges=(0, 100), res=list()):
        """处理数字列表 如 1,2,3,6"""
        val_list = val.split(',')
        for tmp_val in val_list:
            tmp_val = int(tmp_val)
            if tmp_val >= ranges[0] and tmp_val <= ranges[1]:
                res.append(tmp_val)
        return res
    
    def handle_star(val, ranges=(0, 100), res=list()):
        """处理星号"""
        if val == '*':
            tmp_val = ranges[0]
            while tmp_val <= ranges[1]:
                res.append(tmp_val)
                tmp_val = tmp_val + 1
        return res
    
    def handle_starnum(val, ranges=(0, 100), res=list()):
        """星号/数字 组合 如 */3"""
        tmp = val.split('/')
        val_step = int(tmp[1])
        if val_step < 1:
            return res
        val_tmp = int(tmp[1])
        while val_tmp <= ranges[1]:
            res.append(val_tmp)
            val_tmp = val_tmp + val_step
        return res
    
    def handle_range(val, ranges=(0, 100), res=list()):
        """处理区间 如 8-20"""
        tmp = val.split('-')
        range1 = int(tmp[0])
        range2 = int(tmp[1])
        tmp_val = range1
        if range1 < 0:
            return res
        while tmp_val <= range2 and tmp_val <= ranges[1]:
            res.append(tmp_val)
            tmp_val = tmp_val + 1
        return res
    
    def handle_rangedv(val, ranges=(0, 100), res=list()):
        """处理区间/步长 组合 如 8-20/3 """
        tmp = val.split('/')
        range2 = tmp[0].split('-')
        val_start = int(range2[0])
        val_end = int(range2[1])
        val_step = int(tmp[1])
        if (val_step < 1) or (val_start < 0):
            return res
        val_tmp = val_start
        while val_tmp <= val_end and val_tmp <= ranges[1]:
            res.append(val_tmp)
            val_tmp = val_tmp + val_step
        return res
    
    def parse_conf(conf, ranges=(0, 100), res=list()):
        """解析crontab 五个时间参数中的任意一个"""
        #去除空格,再拆分
        conf = conf.strip(' ').strip(' ')
        conf_list = conf.split(',')
        other_conf = []
        number_conf = []
        for conf_val in conf_list:
            if match_cont(PATTEN['number'], conf_val):
                #记录拆分后的纯数字参数
                number_conf.append(conf_val)
            else:
                #记录拆分后纯数字以外的参数,如通配符 * , 区间 0-8, 及 0-8/3 之类
                other_conf.append(conf_val)
        if other_conf:
            #处理纯数字外各种参数
            for conf_val in other_conf:
                for key, ptn in PATTEN.items():
                    if match_cont(ptn, conf_val):
                        res = PATTEN_HANDLER[key](val=conf_val, ranges=ranges, res=res)
        if number_conf:
            if len(number_conf) > 1 or other_conf:
                #纯数字多于1,或纯数字与其它参数共存,则数字作为时间列表
                res = handle_nlist(val=','.join(number_conf), ranges=ranges, res=res)
            else:
                #只有一个纯数字存在,则数字为时间 间隔
                res = handle_num(val=number_conf[0], ranges=ranges, res=res)
        return res
    
    def parse_crontab_time(conf_string):
        """
        解析crontab时间配置参数
        Args:
            conf_string  配置内容(共五个值:分 时 日 月 周)
                         取值范围 分钟:0-59 小时:1-23 日期:1-31 月份:1-12 星期:0-6(0表示周日)
        Return:
        crontab_range    list格式,分 时 日 月 周 五个传入参数分别对应的取值范围
        """
        time_limit  = ((0, 59), (1, 23), (1, 31), (1, 12), (0, 6))
        crontab_range = []
        clist = []
        conf_length = 5
        tmp_list = conf_string.split(' ')
        for val in tmp_list:
            if len(clist) == conf_length:
                break
            if val:
                clist.append(val)
    
        if len(clist) != conf_length:
            return -1, 'config error whith [%s]' % conf_string
        cindex = 0
        for conf in clist:
            res_conf = []
            res_conf = parse_conf(conf, ranges=time_limit[cindex], res=res_conf)
            if not res_conf:
                return -1, 'config error whith [%s]' % conf_string
            crontab_range.append(res_conf)
            cindex = cindex + 1
        return 0, crontab_range
    
    def time_match_crontab(crontab_time, time_struct):
        """
        将时间戳与crontab配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
        Args:
            crontab_time____crontab配置中的五个时间(分 时 日 月 周)参数对应时间取值范围
            time_struct____ 某个整型时间戳,如:1375027200 对应的 分 时 日 月 周
        Return:
        tuple 状态码, 状态描述
        """
        cindex = 0
        for val in time_struct:
            if val not in crontab_time[cindex]:
                return 0, False
            cindex = cindex + 1
        return 0, True
    
    def close_to_cron(crontab_time, time_struct):
        """coron的指定范围(crontab_time)中 最接近 指定时间 time_struct 的值"""
        close_time = time_struct
        cindex = 0
        for val_struct in time_struct:
            offset_min = val_struct
            val_close = val_struct
            for val_cron in crontab_time[cindex]:
                offset_tmp = val_struct - val_cron
                if offset_tmp > 0 and offset_tmp < offset_min:
                    val_close = val_struct
                    offset_min = offset_tmp
            close_time[cindex] = val_close
            cindex = cindex + 1
        return close_time
    
    def cron_time_list(
            cron_time,
            year_num=int(get_str_time(time.time(), "%Y")),
            limit_start=get_str_time(time.time(), "%Y%m%d%H%M"),
            limit_end=get_str_time(time.time() + 86400, "%Y%m%d%H%M")
        ):
        #print "\nfrom ", limit_start , ' to ' ,limit_end
        """
        获取crontab时间配置参数取值范围内的所有时间点 的 时间戳
        Args:
            cron_time 符合crontab配置指定的所有时间点
            year_num____指定在哪一年内 获取
            limit_start 开始时间
        Rturn:
            List  所有时间点组成的列表(年月日时分 组成的时间,如2013年7月29日18时56分:201307291856)
        """
        #按小时 和 分钟组装
        hour_minute = []
        for minute in cron_time[0]:
            minute = str(minute)
            if len(minute) < 2:
                minute = '0%s' % minute
            for hour in cron_time[1]:
                hour = str(hour)
                if len(hour) < 2:
                    hour = '0%s' % hour
                hour_minute.append('%s%s' % (hour, minute))
        #按天 和 小时组装
        day_hm = []
        for day in cron_time[2]:
            day = str(day)
            if len(day) < 2:
                day = '0%s' % day
            for hour_mnt in hour_minute:
                day_hm.append('%s%s' % (day, hour_mnt))
        #按月 和 天组装
        month_dhm = []
        #只有30天的月份
        month_short = ['02', '04', '06', '09', '11']
        for month in cron_time[3]:
            month = str(month)
            if len(month) < 2:
                month = '0%s' % month
            for day_hm_s in day_hm:
                if month == '02':
                    if (((not year_num % 4 ) and (year_num % 100)) or (not year_num % 400)):
                        #闰年2月份有29天
                        if int(day_hm_s[:2]) > 29:
                            continue
                    else:
                        #其它2月份有28天
                        if int(day_hm_s[:2]) > 28:
                            continue
                if month in month_short:
                    if int(day_hm_s[:2]) > 30:
                        continue
                month_dhm.append('%s%s' % (month, day_hm_s))
        #按年 和 月组装
        len_start = len(limit_start)
        len_end = len(limit_end)
        month_dhm_limit = []
        for month_dhm_s in month_dhm:
            time_ymdhm = '%s%s' % (str(year_num), month_dhm_s)
            #开始时间\结束时间以外的排除
            if (int(time_ymdhm[:len_start]) < int(limit_start)) or \
             (int(time_ymdhm[:len_end]) > int(limit_end)):
                continue
            month_dhm_limit.append(time_ymdhm)
        if len(cron_time[4]) < 7:
            #按不在每周指定时间的排除
            month_dhm_week = []
            for time_minute in month_dhm_limit:
                str_time = time.strptime(time_minute, '%Y%m%d%H%M%S')
                if str_time.tm_wday in cron_time[4]:
                    month_dhm_week.append(time_minute)
            return month_dhm_week
        return month_dhm_limit
    
    #crontab时间参数各种写法 的 正则匹配
    PATTEN = {
        #纯数字
        'number':'^[0-9]+$',
        #数字列表,如 1,2,3,6
        'num_list':'^[0-9]+([,][0-9]+)+$',
        #星号 *
        'star':'^\*$',
        #星号/数字 组合,如 */3
        'star_num':'^\*\/[0-9]+$',
        #区间 如 8-20
        'range':'^[0-9]+[\-][0-9]+$',
        #区间/步长 组合 如 8-20/3
        'range_div':'^[0-9]+[\-][0-9]+[\/][0-9]+$'
        #区间/步长 列表 组合,如 8-20/3,21,22,34
        #'range_div_list':'^([0-9]+[\-][0-9]+[\/][0-9]+)([,][0-9]+)+$'
        }
    #各正则对应的处理方法
    PATTEN_HANDLER = {
        'number':handle_num,
        'num_list':handle_nlist,
        'star':handle_star,
        'star_num':handle_starnum,
        'range':handle_range,
        'range_div':handle_rangedv
    }
    
    def isdo(strs,tips=None):
        """
        判断是否匹配成功!
        """
        try:
            tips = tips==None and "文件名称格式错误:job_月-周-天-时-分_文件名.txt" or tips
            timer = strs.replace('@',"*").replace('%','/').split('_')[1]
            month,week,day,hour,mins = timer.split('-')
            conf_string = mins+" "+hour+" "+day+" "+month+" "+week
            res, desc = parse_crontab_time(conf_string)
            if res == 0:
                cron_time = desc
            else:
                return False
    
            now =FDateTime.now()
            now = FDateTime.datetostring(now, "%Y%m%d%H%M00")
    
            time_stamp = FDateTime.strtotime(now, "%Y%m%d%H%M00")
    
            #time_stamp = int(time.time())
            #解析 时间戳对应的 分 时 日 月 周
            time_struct = get_struct_time(time_stamp)
            match_res = time_match_crontab(cron_time, time_struct)
            return match_res[1]
        except:
            print tips
            return False
    
    def main():
        """测试用实例"""
        #crontab配置中一行时间参数
        #conf_string = '*/10 * * * * (cd /opt/pythonpm/devpapps; /usr/local/bin/python2.5 data_test.py>>output_error.txt)'
        conf_string = '*/10 * * * *'
        #时间戳
        time_stamp = int(time.time())
    
        #解析crontab时间配置参数 分 时 日 月 周 各个取值范围
        res, desc = parse_crontab_time(conf_string)
    
        if res == 0:
            cron_time = desc
        else:
            print desc
            sys, exit(-1)
    
        print "\nconfig:", conf_string
        print "\nparse result(range for crontab):"
    
        print " minute:", cron_time[0]
        print " hour: ", cron_time[1]
        print " day: ", cron_time[2]
        print " month: ", cron_time[3]
        print " week day:", cron_time[4]
    
        #解析 时间戳对应的 分 时 日 月 周
        time_struct = get_struct_time(time_stamp)
        print "\nstruct time(minute hour day month week) for %d :" % \
             time_stamp, time_struct
    
        #将时间戳与crontab配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
        match_res = time_match_crontab(cron_time, time_struct)
        print "\nmatching result:", match_res
    
        #crontab配置设定范围中最近接近时指定间戳的一组时间
        most_close = close_to_cron(cron_time, time_struct)
        print "\nin range of crontab time which is most colse to struct ", most_close
    
        time_list = cron_time_list(cron_time)
        print "\n\n %d times need to tart-up:\n" % len(time_list)
        print time_list[:10], '...'
    
    if __name__ == '__main__':
        #请看 使用实例
        strs = 'job_@-@-@-@-@_test02.txt.sh'
        print isdo(strs)
    
        #main()0")
    

    转载请注明:爱开源 » python实现的解析crontab配置文件代码

  • 被遗忘的Logrotate

    我发现很多人的服务器上都运行着一些诸如每天切分Nginx日志之类的CRON脚本,大家似乎遗忘了Logrotate,争相发明自己的轮子,这真是让人沮丧啊!就好比明明身边躺着现成的性感美女,大家却忙着自娱自乐,罪过!

    Logrotate的介绍

    显而易见,Logrotate是基于CRON来运行的,其脚本是「/etc/cron.daily/logrotate」:

    #!/bin/sh
    
    /usr/sbin/logrotate /etc/logrotate.conf
    EXITVALUE=$?
    if [ $EXITVALUE != 0 ]; then
        /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
    fi
    exit 0
    
    <span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">
    
    实际运行时,Logrotate会调用配置文件「/etc/logrotate.conf」:</span>
    
    # see "man logrotate" for details
    # rotate log files weekly
    weekly
    
    # keep 4 weeks worth of backlogs
    rotate 4
    
    # create new (empty) log files after rotating old ones
    create
    
    # uncomment this if you want your log files compressed
    #compress
    
    # RPM packages drop log rotation information into this directory
    include /etc/logrotate.d
    
    # no packages own wtmp -- we'll rotate them here
    /var/log/wtmp {
        monthly
        minsize 1M
        create 0664 root utmp
        rotate 1
    }
    
    # system-specific logs may be also be configured here.
    
    <span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">
    这里的设置可以理解为Logrotate的缺省值,当然了,可以我们在「/etc/logrotate.d」目录里放置自己的配置文件,用来覆盖Logrotate的缺省值。</span>
    

    Logrotate的演示

    按天保存一周的Nginx日志压缩文件,配置文件为「/etc/logrotate.d/nginx」:

    /usr/local/nginx/logs/*.log {
        daily
        dateext
        compress
        rotate 7
        sharedscripts
        postrotate
            kill -USR1 `cat /var/run/nginx.pid`
        endscript
    }
    
    <span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">
    如果你等不及CRON,可以通过如下命令来手动执行:</span>
    
    shell> logrotate -f /etc/logrotate.d/nginx
    

    当然,正式执行前最好通过Debug选项来验证一下,这对调试也很重要:

    shell> logrotate -d -f /etc/logrotate.d/nginx
    

    BTW:类似的还有Verbose选项,这里就不多说了。

    Logrotate的疑问

    问题:sharedscripts的作用是什么?

    大家可能注意到了,我在前面Nginx的例子里声明日志文件的时候用了星号通配符,也就是说这里可能涉及多个日志文件,比如:access.log和error.log。说到这里大家或许就明白了,sharedscripts的作用是在所有的日志文件都轮转完毕后统一执行一次脚本。如果没有配置这条指令,那么每个日志文件轮转完毕后都会执行一次脚本。

    问题:rotate和maxage的区别是什么?

    它们都是用来控制保存多少日志文件的,区别在于rotate是以个数为单位的,而maxage是以天数为单位的。如果我们是以按天来轮转日志,那么二者的差别就不大了。

    问题:为什么生成日志的时间是凌晨四五点?

    前面我们说过,Logrotate是基于CRON运行的,所以这个时间是由CRON控制的,具体可以查询CRON的配置文件「/etc/crontab」,可以手动改成如23:59等时间执行:

    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    HOME=/
    
    # run-parts
    01 * * * * root run-parts /etc/cron.hourly
    59 23 * * * root run-parts /etc/cron.daily
    22 4 * * 0 root run-parts /etc/cron.weekly
    42 4 1 * * root run-parts /etc/cron.monthly
    
    <span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">
    如果使用的是新版CentOS,那么配置文件为:/etc/anacrontab。</span>
    

    问题:如何告诉应用程序重新打开日志文件?

    以Nginx为例,是通过postrotate指令发送USR1信号来通知Nginx重新打开日志文件的。但是其他的应用程序不一定遵循这样的约定,比如说MySQL是通过flush-logs来重新打开日志文件的。更有甚者,有些应用程序就压根没有提供类似的方法,此时如果想重新打开日志文件,就必须重启服务,但为了高可用性,这往往不能接受。还好Logrotate提供了一个名为copytruncate的指令,此方法采用的是先拷贝再清空的方式,整个过程中日志文件的操作句柄没有发生改变,所以不需要通知应用程序重新打开日志文件,但是需要注意的是,在拷贝和清空之间有一个时间差,所以可能会丢失部分日志数据。

    BTW:MySQL本身在support-files目录已经包含了一个名为mysql-log-rotate的脚本,不过它比较简单,更详细的日志轮转详见「Rotating MySQL Slow Logs Safely」。

    熟悉Apache的朋友可能会记得cronolog,不过Nginx并不支持它,有人通过mkfifo命令曲线救国,先给日志文件创建管道,再搭配cronolog轮转,虽然理论上没有问题,但效率上有折扣。另外,Debian/Ubuntu下有一个简化版工具savelog,有兴趣可以看看。

    转载请注明:爱开源 » 被遗忘的Logrotate

  • 一个php进程cpu %nice很高的原因详解

    一、 现象描述:

    1、 CPU的%user、%sys占用的CPU不高,但%nice占用了大量的CPU资源,最高占用CPU的60%以上;
    2、 ps -elf中PRI为90,NI为10,top看到PR值为30,NI 10;
    

    问题:为什么从ps中看到的priority值和top中的不同?
    top中的PR是:The priority of the task(取值范围:-20最高,19最低)
    ps中的PRI是:realtime priority(根据 nice( ) 和setpriority( ) 计算,Static priority 取值1-99,Dynamic priority还没有看懂)

    3、sar信息收集

    CPU:
    Linux 2.6.32-279.el6.x86_64 (web2.17173ops.com) 05/09/2014 _x86_64_ (8 CPU)
    
    12:00:04 AM CPU %user %nice %system %iowait %steal %idle
    12:01:01 AM all 0.39 26.67 1.84 30.15 0.00 40.95
    12:02:03 AM all 0.30 24.07 2.74 30.10 0.00 42.80
    12:03:01 AM all 0.27 23.61 1.65 34.48 0.00 40.00
    12:04:02 AM all 0.26 23.37 1.96 34.87 0.00 39.54
    12:05:04 AM all 0.31 24.08 3.74 36.66 0.00 35.21
    12:06:02 AM all 0.43 21.96 2.09 34.93 0.00 40.59
    12:07:16 AM all 0.25 23.66 2.07 59.63 0.00 14.38
    12:08:02 AM all 0.33 30.21 2.01 36.88 0.00 30.57
    

    二、服务器硬/软件:

    Product Name: PowerEdge R410
    CPU:Intel(R) Xeon(R) CPU E5606 @ 2.13GHz
    Memory:24GB 4*6
    OS:Red Hat Enterprise Linux Server release 6.3 (Santiago)
    Web server:nginx version: nginx/1.4.4
    CGI server:php-5.3.21
    

    三、 判断问题:
    1、 NICE资源一般是用户端控制的行为产生;
    2、 除非程序中有大量的使用sleep,或者是调用了nice等函数,对自定义了优先级别,但一般程序不会这么变态;

    四、 查找问题过程:
    1、习惯性认为是程序开发的问题,在代码中不断查找类似sleep、nice的字眼,浪费了一些时间;
    2、ps -elf | grep master,发现php-fpm启动时间不一致,有的是03:57,有的是4:03,如果是crontab定义的,时间肯定不会这么不一致;
    3、查找/etc/crontab,文件里面没有定义任何定时任务;
    4、RHEL6的定时任务被anacrontab接管,anacrontab是crontab的补充,内容如下:(问题也就出在下面红色+备注的那行)

    # cat /etc/anacrontab
    # /etc/anacrontab: configuration file for anacron
    
    # See anacron(8) and anacrontab(5) for details.
    
    SHELL=/bin/sh
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    # the maximal random delay added to the base delay of the jobs
    RANDOM_DELAY=45
    # the jobs will be started during the following hours only
    START_HOURS_RANGE=3-22
    
    #period in days delay in minutes job-identifier command
    1 5 cron.daily nice run-parts /etc/cron.daily <strong>## 日志切割定时任务在此</strong>
    7 25 cron.weekly nice run-parts /etc/cron.weekly
    @monthly 45 cron.monthly nice run-parts /etc/cron.monthly
    

    五、 思考、优化:
    1、不建议在服务器上使用anacrontab,继续使用crontab;(RHEL5不存在此问题);
    2、其实anacrontab使用nice指令也不会出现问题,主要是和php-fpm启动脚本中的restart配合导致这种情况的发生;
    3、php-fpm使用reload或者是kill -USR2,nice都不会生效,会按原PID的优先等级。因为手工启动php-fpm时我们肯定不会带上nice。

    转载请注明:爱开源 » 一个php进程cpu %nice很高的原因详解