Centos 7下利用crontab定時執行任務詳解

一 cron服務apache

cron服務是Linux的內置服務,但它不會開機自動啓動。能夠用如下命令啓動和中止服務:bash

/sbin/service crond start
/sbin/service crond stop
/sbin/service crond restart
/sbin/service crond reload
 
以上分別爲啓動、中止、重啓服務和從新加載配置。
要把cron設爲在開機的時候自動啓動,在 /etc/rc.d/rc.local 腳本中加入 /sbin/service crond start 便可
 

二  查看cron服務

查看當前用戶的crontab,輸入 crontab -lspa

編輯crontab,輸入 crontab -erest

刪除crontab,輸入 crontab -r;code

三 添加任務

crontab -ecrontab

0 */1 * * * commandio

0 */2 * * * commandfunction

查詢任務是否加了:class

crontab -l -u root 配置

#查看root用戶

0 */1 * * * command0 */2 * * * command

 

四 基本格式 

*  *  *  *  *  command

分 時 日 月 周 命令

第1列表示分鐘1~59 每分鐘用*或者 */1表示

第2列表示小時1~23(0表示0點)

第3列表示日期1~31

第4列表示月份1~12

第5列標識號星期0~6(0表示星期天)

第6列要運行的命令

五 crontab 的一些例子以及說明

30 21 * * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每晚的21:30重啓apache。 

 

45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每個月一、十、22日的4 : 45重啓apache。

 

10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每週6、週日的1 : 10重啓apache。 

 

0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示在天天18 : 00至23 : 00之間每隔30分鐘重啓apache。

 
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每星期六的11 : 00 pm重啓apache。

 
* */1 * * * /usr/local/etc/rc.d/lighttpd restart

每一小時重啓apache

 
* 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart

晚上11點到早上7點之間,每隔一小時重啓apache

 
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart

每個月的4號與每週一到週三的11點重啓apache

 
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart

一月一號的4點重啓apache

---恢復內容結束---

一 cron服務

cron服務是Linux的內置服務,但它不會開機自動啓動。能夠用如下命令啓動和中止服務:

/sbin/service crond start
/sbin/service crond stop
/sbin/service crond restart
/sbin/service crond reload
 
以上分別爲啓動、中止、重啓服務和從新加載配置。
要把cron設爲在開機的時候自動啓動,在 /etc/rc.d/rc.local 腳本中加入 /sbin/service crond start 便可
 

二  查看cron服務

查看當前用戶的crontab,輸入 crontab -l

編輯crontab,輸入 crontab -e

刪除crontab,輸入 crontab -r;

三 添加任務

crontab -e

0 */1 * * * command

0 */2 * * * command

查詢任務是否加了:

crontab -l -u root

#查看root用戶

0 */1 * * * command0 */2 * * * command

 

四 基本格式 

*  *  *  *  *  command

分 時 日 月 周 命令

第1列表示分鐘1~59 每分鐘用*或者 */1表示

第2列表示小時1~23(0表示0點)

第3列表示日期1~31

第4列表示月份1~12

第5列標識號星期0~6(0表示星期天)

第6列要運行的命令

五 crontab 的一些例子以及說明

30 21 * * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每晚的21:30重啓apache。 

 

45 4 1,10,22 * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每個月一、十、22日的4 : 45重啓apache。

 

10 1 * * 6,0 /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每週6、週日的1 : 10重啓apache。 

 

0,30 18-23 * * * /usr/local/etc/rc.d/lighttpd restart

上面的例子表示在天天18 : 00至23 : 00之間每隔30分鐘重啓apache。

 
0 23 * * 6 /usr/local/etc/rc.d/lighttpd restart

上面的例子表示每星期六的11 : 00 pm重啓apache。

 
* */1 * * * /usr/local/etc/rc.d/lighttpd restart

每一小時重啓apache

 
* 23-7/1 * * * /usr/local/etc/rc.d/lighttpd restart

晚上11點到早上7點之間,每隔一小時重啓apache

 
0 11 4 * mon-wed /usr/local/etc/rc.d/lighttpd restart

每個月的4號與每週一到週三的11點重啓apache

 
0 4 1 jan * /usr/local/etc/rc.d/lighttpd restart

一月一號的4點重啓apache

相關文章
相關標籤/搜索