Fedora(Linux) 下 crontab 与 at 命令的使用
一、cron
1、cron 与 crontab
cron 是 linux 下定时执行指定命令的一个服务。服务状态相关命令如下:
查看:
# /sbin/service crond status
crond (pid 2840) is running...
禁用:
# /sbin/service crond stop
启动:
# /sbin/service crond start
重启:
# /sbin/service crond restart
2、crontab命令
cron 定时任务也是基于文本的,配置完定时任务后,可以在/var/spool/cron下按照用户名找到对应的定时任务列表。对定时任务的配置是通过crontab进行的。
命令格式:
crontab [-u user] file
crontab [-u user] [-l | -r | -e] [-i]
选项意义:
- -u,用于指定crontab所属用户。若不指定,则默认为用户执行者;
- -l,列出用户当前已经配置的定时任务;
- -r,删除用户定时任务列表;
- -e,修改定时任务列表;
- -i,删除定时任务列表,删除前待用户确认;
其中,第一种格式中,是将当前file中按照一定格式的定时任务列表导入指定用户的crotab中。下面介绍crontab文件格式:
crontab 中定时任务格式:
T1 T2 T3 T4 T5 T6
共有六个字段组成,各个字段之间用空格间隔:
- T1:分钟(0-59)
- T2:小时(0-23)
- T3:天(1-31)
- T4:月(1-12)
- T5:星期(0-6)
- T6:待执行命令(绝对路径标识)
另外:“*”表示连续时间段;“-”表示某个时间范围;“,”表示某个指定的时间点;“/M”表示每M个单位时间;
举例:
#每天晚上22点执行cleartab.sh脚本
00 22 * * * /usr/appwiz/cleartab.sh
#每天晚上十点到凌晨每20分钟清楚一次/log/tmp
*/20 22-00 * * * /bin/rm -rf /home/admin/log/tmp
#每月的1号,10号20号,八点进行文件备份
0 08 1,10,20 6 * /bin/cp -rf /home/admin/workbench /mnt/hgfs/share
#每周一周三上午10点执行脚本echotoH.sh
* 10 * * 1,3 /usr/appwiz/echotoH.sh
备份与恢复:
为防止用户cron任务被意外删除,可进行适当备份,以备后续恢复。
# crontab -l >$HOME/cronBAK/cron
恢复方式:
# crontab cron
二、at命令
at 命令允许用户向 cron 进程提交一个任务,使其在稍后指定时间运行。at命令在提交任务后,保留当前的环境变量。其结果以邮件方式发送给用户,当然可以通过重定向方式将结果输出到指定文件。
1、格式:
at [-V] [-q queue] [-f file] [-mldbv] TIME
atrm [-V] job [job...]
其中:
- -f:用于指定待运行的脚本或命令;
- TIME:用于指定作业运行时间;
2、举例:
# at 19:48
at> find / -name "passwd" -print
at>
job 3 at Sun Feb 5 19:48:00 2012
# date
Sun Feb 5 19:48:59 CST 2012
# cd /var/spool/at/spool
# ll
total 20
-rw------- 1 root root 98 2012-01-12 20:49 a0000101515062
-rw------- 1 root root 255 2012-02-05 15:35 a000020151d627
-rw------- 1 root root 255 2012-02-05 19:48 a000030151d724
-rw-r--r-- 1 root root 205 2012-02-05 15:51 ps.txt
# cat a000030151d724
Subject: Output from your job 3
To: admin
/usr/bin/passwd
find: /usr/share/icons/Mist/32x32/status: Input/output error
find: /usr/share/icons/Mist/scalable: Input/output error
/usr/share/doc/nss_ldap-254/pam.d/passwd
/etc/passwd
/etc/pam.d/passwd
# at -l
3 Sun Feb 5 19:48:00 2012 = root
另,可以通过atrm 指定job号删除计划任务。