crontab 定时任务
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/5 * * * * bash脚本名 每5分钟执行
0 2 * * * bash脚本名 每天凌晨2点执行
0 2 7 * * bash脚本名 每月7号凌晨2点执行
注: day of month + month 与 day of week 不同时使用
crontab命令:
-l: 显示当前用户的任务列表
-l -u username 显示其它用户的任务列表
-e:编辑任务
-r: 移除所有任务
练习.:每周2,4,7备份/var/log/messages文件至/backup/messages/目录中,文件名保存为形如messages-2017-03-27.tar.xz
0 0 * * 2,4,7 /bin/cp -a /var/log/messages backup/messages/messages-`/bin/date "+%Y-%m-%d"`
案例:重定向rm命令,使被删除的文件移动到recycle_bin目录。再写一个定时任务每天删除recycle_bin目录中7天前的文件
1. 添加文件/usr/local/recycle_bin/recycle_bin.sh
#!/bin/bash
count=0
dir=/tmp
if [ -d /tmp/recycle_bin ];then
dir=/tmp/recycle_bin/`date +%F-%H-%M-%S`
mkdir -p $dir
for i in $*;do
count=`echo $i|grep "^-"|wc -l`
if [ $count -ne 1 ];then
mv $i $dir
else
count=0
fi
done
else
mkdir -p /tmp/recycle_bin
dir=/tmp/recycle_bin/`date +%F-%H-%M-%S`
mkdir -p $dir
for i in $*;do
count=`echo $i|grep "^-"|wc -l`
if [ $count -ne 1 ];then
mv $i $dir
else
count=0
fi
done
fi
2. 重定向rm命令
修改~/.bashrc, 如有要对所有用户生效就修改/etc/.bashrc
alias rm='rm -i' 改为:
alias rm='/usr/local/recycle_bin/recycle_bin.sh'
resource ~/.bashrc
3. 添加文件/usr/local/recycle_bin/clear_recycle_bin.sh
#!/bin/bash clear_dir=/tmp/recycle_bin/`date -d "7 day ago" +"%Y-%m-%d"`* #clear_dir=/tmp/recycle_bin/`date %Y-%m-%d`* /bin/rm -rf $clear_dir
4.添加定时任务
crontab -e
30 11 */1 * * /usr/local/recycle_bin/clear_recycle_bin.sh
本文详细介绍了如何使用crontab进行定时任务设置,包括每5分钟、每天凌晨2点和每月7号凌晨2点的执行示例。此外,还探讨了crontab命令的常用选项,如查看、编辑和移除任务。同时,文章提供了一个实战案例,讲解如何创建一个脚本来重定向rm命令,并设置定时任务每天清理回收站中的过期文件。
1333

被折叠的 条评论
为什么被折叠?



