定时任务分为两种,一种是一次性任务,一种周期性任务。

1、一次性任务at

at队列
用来存储尚未执行的任务,一旦执行了就从队列中将任务删除

[root@localhost test]# ll /var/spool/at/spool/
total 0

队列的保存位置/var/spool/at/

[root@localhost spool]# service atd start
Starting atd:                                              [  OK  ]
[root@localhost spool]# ls
anacron  at  cron  lpd  mail  plymouth  postfix

at服务
用来检测和执行任务,每间隔1一分钟就会检查队列中是否有到时的任务.
at工具
用来添加,查看,删除定时任务的工具

[root@localhost test]# date
Fri Apr 11 09:59:34 CST 2014
[root@localhost test]# at 10:02   //新建任务
at> mkdir work
at> <EOT>
job 2 at 2014-04-11 10:02
[root@localhost test]# at 10:05   //新建任务
at> touch file
at> <EOT>
job 3 at 2014-04-11 10:05
[root@localhost test]# at -l    //查看一次性定时任务
1       2014-04-12 08:58 a root
2       2014-04-11 10:02 a root
3       2014-04-11 10:05 a root
[root@localhost test]# at -d 1   //删除定时任务
[root@localhost test]# at -l
2       2014-04-11 10:02 a root
3       2014-04-11 10:05 a root

[root@localhost ~]# at -c 6   //查看任务的详细情况
#!/bin/sh
# atrun uid=0 gid=0
# mail root 0
umask 22

at服务的启动和停止

[root@localhost ~]# service atd status
atd (pid  1175) is running...

atq查看一次性任务

atrm删除一次性任务

[root@localhost ~]# at 11:00
at> rm -rf 1
at> <EOT>
job 5 at 2014-04-11 11:00
[root@localhost ~]# atq
5       2014-04-11 11:00 a root
[root@localhost ~]# atrm 5
[root@localhost ~]# atq


2、周期性任务

crond服务状态

[root@localhost ~]# service crond status
crond (pid  1072) is running...

用户定义的任务位于/var/spool/cron/用户名

[root@localhost ~]# cat /var/spool/cron/zhouyan
0 8 * * * /sbin/service sshd start

cron格式 (man 5 crontab)
min hour day mon week commands
min: 分 00-59
hour: 时 00-23
day: 日 1-31
mon: 月 1-12
week: 周 0-7 0和7都是周日
command:要执行的任务
使用方法
 单一时间 00 03 * * * cmd
,多个时间 00 9,12,22 * * * cmd
- 连续时间 00 9-12 * * * cmd 9-12点
* 所有时间 * * * * * cmd
/ 间隔时间 */5 * * * * cmd 每5分钟

添加计划任务
crontab -e [-u username]添加

[root@localhost ~]# crontab -e
[root@localhost ~]# cat /var/spool/cron/root
#周一到周五每天17:50
50 17 * * 1-5 /bin/ps >>1.log
#每周一、三、五的8点30分
30 8 * * 1,3,5 /usr/bin/uptime >>2.log
#八点到18点之间每隔2个小时
0 8-18/2 * * *  /usr/bin/w >>3.log
#每隔三天
0 0 */3 * * /usr/bin/who >>4.log

crontab -l [-u username]查看

[root@localhost ~]# crontab -l  //默认查看root的任务
#周一到周五每天17:50
50 17 * * 1-5 /bin/ps >>1.log
#每周一、三、五的8点30分
30 8 * * 1,3,5 /usr/bin/uptime >>2.log
#八点到18点之间每隔2个小时
0 8-18/2 * * *  /usr/bin/w >>3.log
#每隔三天
0 0 */3 * * /usr/bin/who >>4.log

[root@localhost ~]# crontab -e -u zhouyan
[root@localhost ~]# crontab -l -u zhouyan  //查看指定用户的任务
0 8 * * * /sbin/service sshd start

crontab -r [-u username]删除

[root@localhost ~]# crontab -r -u zhouyan
[root@localhost ~]# crontab -l -u zhouyan
no crontab for zhouyan