歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux Crontab 定時任務

Linux Crontab 定時任務

日期:2017/2/28 14:50:54   编辑:Linux教程

一、Crontab介紹

crontab命令的功能是在一定的時間間隔調度一些命令的執行。

1.1 /etc/Crontab文件

在/etc目錄下有一個crontab文件,這裡存放有系統運行的一些調度程序。每個用戶可以建立自己的調度crontab(在/var/spool/cron目錄下)。
以下是我本機上的crontab文件,

[root@localhost etc]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

二、Crontab使用說明

2.1 Crontab基本語法

usage: crontab [-u user] file

crontab [-u user] [ -e | -l | -r ]

(default operation is replace, per 1003.2)

-e (edit user's crontab)

-l (list user's crontab)

-r (delete user's crontab)

-i (prompt before deleting user's crontab)

-s (selinux context)


其中,file是命令文件的名字。如果在命令行中指定了這個文件,那麼執行crontab命令,則將這個文件拷貝到crontabs目錄下;如果在命令行中沒有制定這個文件,crontab命令將接受標准輸入(鍵盤)上鍵入的命令,並將他們也存放在crontab目錄下。

如果想查看Crontab更詳細的語法及使用幫助,則可以通過man crontab來查看幫助。

2.2 Crontab 格式說明

我們可以用crontab -e 添加要執行的命令。

添加的命令必須以如下格式:

* * * * * /需執行命令的路徑

前五個字段可以取整數值,指定何時開始工作,第六個域是字符串,即命令字段,其中包括了crontab調度執行的命令。 各個字段之間用spaces和tabs分割。

前5個字段分別表示:

分鐘:0-59

小時:1-23

日期:1-31

月份:1-12

星期:0-6(0表示周日)


還可以用一些特殊符號:

*: 表示任何時刻

,: 表示分割

  -:表示一個段,如第二端裡: 1-5,就表示1到5點

/n : 表示每個n的單位執行一次,如第二段裡,*/1, 就表示每隔1個小時執行一次命令。也可以寫成1-23/1.

一些示例:

00 8,12,16 * * * /test/command.sh

30 2 * * * /test/command.sh

10 8,12,16 * * * /test/command.sh

10 8,12,16 * * * /test/command.sh

10 8,12,16 * * * /test/command.sh



43 21 * * * 21:43 執行

15 05 * * *    05:15 執行

0 17 * * * 17:00 執行

0 17 * * 1 每周一的 17:00 執行

0,10 17 * * 0,2,3 每周日,周二,周三的 17:00和 17:10 執行

0-10 17 1 * * 毎月1日從 17:00到17:10 毎隔1分鐘 執行

0 0 1,15 * 1 毎月1日和 15日和周一的 0:00 執行

42 4 1 * *     毎月1日的 4:42分 執行

0 21 * * 1-6   周一到周六 21:00 執行

0,10,20,30,40,50 * * * * 每隔10分 執行

*/10 * * * *        每隔10分 執行

* 1 * * *         從1:0到1:59 每隔1分鐘 執行

0 1 * * *         1:00 執行

0 */1 * * *        毎時0分 每隔1小時 執行

0 * * * *         毎時0分 每隔1小時 執行

2 8-20/3 * * *      8:02,11:02,14:02,17:02,20:02 執行

30 5 1,15 * *       1日和15日的5:30 執行

Copyright © Linux教程網 All Rights Reserved