> Linux命令 >

Linux 下执行定时任务 crontab 命令详解

1、先来一个小小的例子
查看当前路径:

[root@root test]# pwd
/home/admin/test
[root@root test]# crontab -l
查看当前用户的定时任务 也可以 crontab -uroot -l查看指定用户的定时任务。
千万不要忘了中间的 sh 表示用户拿什么来执行命令

00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
建立一个用定时任务跑的bash脚本:

[root@root test]# touch test.sh
[root@root test]# vim test.sh
编辑如下内容,将系统当前时间输出到 console.txt 文件然后保存,增加可执行权限

/bin/echo `date` > /home/admin/test/console.txt
[root@root test]# ll
total 8
-rw-r--r-- 1 root root 29 Mar 27 21:31 console.txt
-rwxr-xr-x 1 root root 48 Mar 27 21:28 test.sh
[root@root test]# chmod +x ./test.sh
追加 crontab 定时任务,每分钟触发:

[root@root test]# crontab -e
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
*  *  * * * sh /home/admin/test/test.sh
前面是已经存在的定时任务,后面执行test.sh脚本的是追加的
保存后提示已经装载了新的定时任务

"/tmp/crontab.HauiiV" 3L, 143C written
crontab: installing new crontab
再次查看定时任务列表,可以看到定时任务已经添加

[root@root test]# crontab -l
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh
*  *  * * * sh /home/admin/test/test.sh
[root@root test]#
查看console.txt有没有每分钟写入console.txt文件

[root@root test]# vim console.txt
Fri Mar 27 21:40:01 EDT 2015
可以看到最近一次的写入时间。

2、看看crontab 的时间表达式
基本格式 :
*  *  *  *  *  command
分 时 日 月 周 命令


然后来几个实际的例子:

分 时 日 月 星期 要运行的命令
第1列分钟0~59
第2列小时0~23(0表示子夜)
第3列日1~31
第4列月1~12
第5列星期0~7(0和7表示星期天)
第6列要运行的命令


实例1:每1分钟执行一次myCommand
* * * * * myCommand

实例2:每小时的第3和第15分钟执行
3,15 * * * * myCommand

实例3:在上午8点到11点的第3和第15分钟执行
3,15 8-11 * * * myCommand

实例4:每隔两天的上午8点到11点的第3和第15分钟执行
3,15 8-11 */2  *  * myCommand

实例5:每周一上午8点到11点的第3和第15分钟执行
3,15 8-11 * * 1 myCommand

实例6:每晚的21:30重启smb
30 21 * * * /etc/init.d/smb restart

实例7:每月1、10、22日的4 : 45重启smb
45 4 1,10,22 * * /etc/init.d/smb restart

实例8:每周六、周日的1 : 10重启smb
10 1 * * 6,0 /etc/init.d/smb restart

实例9:每天18 : 00至23 : 00之间每隔30分钟重启smb
0,30 18-23 * * * /etc/init.d/smb restart

实例10:每星期六的晚上11 : 00 pm重启smb
0 23 * * 6 /etc/init.d/smb restart

实例11:每一小时重启smb
* */1 * * * /etc/init.d/smb restart

实例12:晚上11点到早上7点之间,每隔一小时重启smb
0 23-7 * * * /etc/init.d/smb restart
3、其他命令介绍
名称 : crontab

使用权限 : 所有使用者

使用方式 :

crontab file [-u user]-用指定的文件替代目前的crontab。

crontab-[-u user]-用标准输入替代目前的crontab.

crontab-1[user]-列出用户目前的crontab.

crontab-e[user]-编辑用户目前的crontab.

crontab-d[user]-删除用户目前的crontab.

crontab-c dir- 指定crontab的目录。
4、crond 安装与配置服务
安装crontab:

yum install crontabs

服务操作说明:

/sbin/service crond start //启动服务

/sbin/service crond stop //关闭服务

/sbin/service crond restart //重启服务

/sbin/service crond reload //重新载入配置

查看crontab服务状态:

service crond status

手动启动crontab服务:

service crond start

查看crontab服务是否已设置为开机启动,执行命令:

ntsysv

加入开机自动启动:

chkconfig –level 35 crond on


(责任编辑:IT)