ubuntu系统定时运行 crontab

1,crontab是个啥?

ubuntu系统自带cron工具,cron是一个系统上的定时工具,用它的好处在于,不同的程序可以用同一个计时器,这样就省得不同程序各自sleep了,另外它还支持比较多的个性化功能,比如每月1号执行一次,

2,crontab怎么用?

crontab是一个和当前用户绑定的命令,一个用户有一个用户的定时配置文件,文件位置/var/spool/cron

crontab -l|-r|-e|-i 用户名
#-l:显示用户定时文件的内容
#-r:删除用户定时文件
#-i:删除用户定时文件的时候给个提示,常用-ri
#-e:编辑用户的crontab文件,第一次用可能让你选择编辑器,

登录系统用户,并且为用户创建定时文件:

crontab -e
#打开一个配置文件,并且让用户输入crontab命令

输入命令并且保存:

* * * * * /usr/bin/python /home/center/temp/crontest/logout.py
#命令的意思是每隔一分钟执行一次logout.py文件,ps:建议使用绝对命令

本人logout.py中的内容:

#!/usr/bin/python
import time
f=open("/home/center/temp/crontest/test.log","a")
t = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
str1 = '执行时间:' + t + '\n'
f.write(str1)
f.close()

crontab命令格式是这样的:

接下来需要启动cron服务

sudo service cron start 
sudo service cron restart    #重启
sudo service cron stop    #关闭

启动成功以后使用ps查看后台进程,就会多一个这样的

root       948  0.0  0.0  30748  3272 ?        Ss   16:28   0:00 /usr/sbin/cron -f

那么问题来了,如果开启了crontab服务的电脑重启了以后,服务还有么?答案是,,还有的。本人亲测

3,crontab定时格式详解

占位符含义

每个字段代表的含义及取值范围如下:
  Minute :分钟(0-59),表示每个小时的第几分钟执行该任务
  Hour : 小时(1-23),表示每天的第几个小时执行该任务
  Day : 日期(1-31),表示每月的第几天执行该任务
  Month : 月份(1-12),表示每年的第几个月执行该任务
  DayOfWeek : 星期(0-6,0代表星期天),表示每周的第几天执行该任务

特殊符号含义

  “*” ,代表所有的取值范围内的数字;
  “/” , 代表”每”(“*/5”,表示每5个单位);
  “-” , 代表从某个数字到某个数字(“1-4”,表示1-4个单位);
  “,” ,分开几个离散的数字;

例子:

每分钟执行 * * * * *
每五分钟执行 */5 * * * *
每小时执行 0 * * * *
每天执行 0 0 * * *
每周执行 0 0 * * 0
每月执行 0 0 1 * *
每年执行 0 0 1 1 *

5 * * * * ls /*指定每小时的第5分钟执行一次ls命令*/ 
30 5 * * * ls /*指定每天的 5:30 执行ls命令*/ 
30 7 8 * * ls /*指定每月8号的7:30分执行ls命令*/ 
50 7 * * * root run-parts /etc/cron.daily /*每天7:50以root 身份执行/etc/cron.daily目录中的所有可执行文件*/

*/2 8-20 * * * /usr/bin/backup   每天8点到晚上8点間隔2分鐘执行一次

4,使用定时工具做个系统监测程序

checkstatus.sh

#!/bin/bash

hdiska=`df -h / | awk 'NR==2{print $4}'`;
temp=`cat /sys/class/thermal/thermal_zone0/temp`;
#echo $hdiska;
tempz=`expr $temp / 1000`;
#printf "%dC\n" $tempz;
#freem=`free -h | awk 'NR==2{print $4}'`;
freem=`free | awk 'NR==2{print ($2-$3)/1024}'`;
#echo $freem;
dura=`cat /proc/uptime |awk '{run_day=$1 / 86400;run_hour=($1 % 86400)/3600;printf("%dd%dh ",run_day,run_hour)}'`;
#echo $dura;
#printf 'disk-aval:%s tempreture:%dC RAM-aval:%s run-time:%s \n' $hdiska $tempz $freem $dura;
cpuload=`vmstat 2 3 |awk 'NR==5 {print $13+$14}'`;
#echo $cpuload;
tmstr=`date +%Y-%m-%d_%H:%M:%S`;

sysload=`top -bn 3 -d 1 |grep -e "load" |awk 'NR==3 {print $12}'|sed 's/,$//g'`;
#echo $sysload;

printf '%s 可用空间:%s 核心温度:%dC 内存余量:%sM cpu负载:%s%% 运行时间:%s 系统负载:%s \n' $tmstr $hdiska $tempz $freem $cpuload $dura $sysload;
#echo `date +%Y-%m-%d\ %H:%M:%S`;
exit 0;

checkpid.sh

#!/bin/bash
pid="/usr/bin/redis-server";

txt=`ps -aux|grep $pid |grep -v grep |awk 'NR==1'`;
tmstr=`date +%Y-%m-%d_%H:%M:%S`;
echo $tmstr $txt;

exit 0;

做好了以后把这俩脚本添加到定时程序中crontab -e

#*/10 * * * * /bin/bash /home/teamhd/temp/tools/checkstatus.sh >> /home/teamhd/temp/tools/state.log 
#*/10 * * * * /bin/bash /home/teamhd/temp/tools/checkpid.sh >> /home/teamhd/temp/tools/pidstate.log

运行一段时间以后,把生成的log带走拿去解析一下

# #!coding=utf_8

"""整理linux记录的运行状态数据 """

import os
from openpyxl import Workbook


# # ###系统state
wb=Workbook()    #要用先实例话一下
ws=wb.active    #获取一个活跃的工作表
ws.title="sheet_daqing"    #工作表的名称为:xxx
ws.append(['time',"hard-drive-free","tempreture","memory-free",'cpu-load','run-time'])    #整行写入
# ws.append(["daqing","12","female"])
# ws["A4"]="hehehe"    #向指定单元格写入
filename='./state.log'
with open(filename,'r+',encoding='UTF-8') as f:
    aline=f.readline()
    idx=0
    while aline:
        # print(aline,'---------')
        acell=aline.split()
        timedtl=acell[0]
        diskdtl=acell[1].split(':')[1]
        tempdtl=acell[2].split(":")[1]
        memdtl=acell[3].split(":")[1]
        cpudtl=acell[4].split(":")[1]
        runtimectl=acell[5].split(":")[1]
        # print(timedtl,diskdtl,tempdtl,memdtl,cpudtl,runtimectl)
        ws.append([timedtl,diskdtl,tempdtl,memdtl,cpudtl,runtimectl])
        aline=f.readline()
        idx+=1
        print(idx)
        # break
wb.save("systemstate.xlsx")    #保存


# ###进程state


# wb=Workbook()    #要用先实例话一下
# ws=wb.active    #获取一个活跃的工作表
# ws.title="sheet_daqing"    #工作表的名称为:xxx
# ws.append(['time',"pid","cpu-load","memory-load",'rss'])    #整行写入
# # ws.append(["daqing","12","female"])
# # ws["A4"]="hehehe"    #向指定单元格写入
# filename='./pidstate.log'
# with open(filename,'r+',encoding='UTF-8') as f:
#     aline=f.readline()
#     idx=0
#     while aline:
#         # print(aline,'---------')
#         acell=aline.split()
#         timedtl=acell[0]
#         piddtl=acell[2]
#         cpudtl=acell[3]+'%'
#         memdtl=acell[4]+'%'
#         rssdtl=str(round(int(acell[6])/1024,2))+'M'

#         # print(timedtl,diskdtl,tempdtl,memdtl,cpudtl,runtimectl)
#         ws.append([timedtl,piddtl,cpudtl,memdtl,rssdtl])
#         aline=f.readline()
#         idx+=1
#         print(idx)
#         # break
# wb.save("appstate.xlsx")    #保存

 

posted @ 2020-02-10 17:18  0点0度  阅读(1298)  评论(0编辑  收藏  举报