初识crontab
说实话,对于Linux许多shell和工具,我都没研究过。除了写过点代码,熟记几个命令,其它基本上没什么突出的本事——有点担心简历上的文字了。
对于crontab,我一直只闻其名,未真正接触过。这次算有点认识了。
我一直想做一下清除日志的事情,因为无意中发现/var/log有20多MB。在周末做了压力测试后,竟然达到GB级别。后来查了些资料,可以通过crontab进行定时任务,于是了解了一下crontab。
其实crontab使用也简单,比如每隔一分钟,就做删除一个文件。可以这样:输入crond -e,选择一个编辑器,如vim,加入
0-59/1 * * * * rm /root/a.txt
表示每隔1分钟都删除一次a.txt
先前,我执行的命令是:0-59/1 * * * * ll,即每一分钟都列出当前目录。结果等了一分钟,毫无效果,于是一直上网搜索“crontab不执行”,却没什么有用的信息。后来我用删除的命令来测试,才发现的确会执行,每当我touch出一个a.txt文件后,时间跳过分钟时,这个文件就被删除了,——原来,命令已执行,只是我不知而已。
成功后就十分的兴奋,试试传说中的定时任务。如:
01 00 * * * /root/my_test.sh
表示每天00:01分执行一次my_test.sh脚本。
开启日志crontab的日志,编辑文件/etc/rsyslog.d/50-default.conf,打开注释:
cron.* /var/log/cron.log
重启crontab服务:
/etc/init.d/cron restart
系统中有很多定时任务,看看/etc:
[email protected]:etc# ls cron* crontab cron.d: anacron sysstat cron.daily: 0anacron apache2 apt dpkg logrotate ntp passwd sysstat upstart cron.hourly: cron.monthly: 0anacron cron.weekly: 0anacron fstrim
每小时、每一天、每一周、每一月都分门别类地放在。
开始时,我以为要自己写个清理日志的脚本,放到crontab中,后来发现有一个叫logrotate的东东,这里看看与日志回滚有关的配置文件logrotate:
cat logrotate #!/bin/sh # Clean non existent log file entries from status file cd /var/lib/logrotate test -e status || touch status head -1 status > status.clean sed 's/"//g' status | while read logfile date do [ -e "$logfile" ] && echo "\"$logfile\" $date" done >> status.clean mv status.clean status test -x /usr/sbin/logrotate || exit 0 /usr/sbin/logrotate /etc/logrotate.conf
看看上面提到的 /etc/logrotate.conf文件:
cat /etc/logrotate.conf # see "man logrotate" for details # rotate log files weekly #weekly # everyday Late Lee... daily # use the syslog group by default, since this is the owning group # of /var/log/syslog. su root syslog # keep 4 weeks worth of backlogs # keep 2 Late Lee rotate 2 # create new (empty) log files after rotating old ones create # uncomment this if you want your log files compressed compress # packages drop log rotation information into this directory include /etc/logrotate.d # no packages own wtmp, or btmp -- we'll rotate them here /var/log/wtmp { missingok monthly create 0664 root utmp rotate 1 } /var/log/btmp { missingok monthly create 0660 root utmp rotate 1 } # system-specific logs may be configured here
在这个文件就可以配置是按天还是按周进行日志回滚。
有试验过程中出现提示:No MTA installed, discarding output,查了资料,网上有解决方法, 在每条定时脚本后面加入“>/dev/null 2>&1”就可以解决No MTA installed, discarding output的问题。
鉴于自己不是搞运维的,实际中使用crontab也不是很多,所以只能是”初识crontab“,深入的东西,待有机会再去了解了解。
李迟,2014年12月18日中午
近来经济拮据,如本文对阁下有帮助,可慷慨解囊赞助笔者以输出更多好文章。
支付宝[email protected] 或 微信fly_camel_fly 均可。感谢!
本文固定链接: /using-gnu-linux/little-about-crontab.html