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

先来一个小小的例子

[root@root test]# pwd
/home/admin/test 
[root@root test]# crontab -l
00 02 * * * sh /home/admin/optbash/dailyBackup.sh
00 02 * * * sh /home/admin/optbash/deleteDebugSql.sh

查看当前用户的定时任务 也可以 crontab -uroot -l 查看指定用户的定时任务。 千万不要忘了中间的 sh 表示用户拿什么来执行命令

建立一个用定时任务跑的bash脚本(将系统当前时间输出到 console.txt 文件):

[root@root test]# touch test.sh
[root@root test]# vim test.sh
/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脚本的是追加的 保存后提示已经装载了新的定时任务

再次查看定时任务列表,可以看到定时任务已经添加

查看console.txt有没有每分钟写入console.txt文件

可以看到最近一次的写入时间。

看看crontab 的时间表达式

然后来几个实际的例子:

其他命令介绍

crond 安装与配置服务

Last updated

Was this helpful?