Linux-任務調度cron

linux 系統則是由 cron (crond) 這個系統服務來控制的。Linux 系統上面原本就有非常多的計劃性工作,因此這個系統服務是默認啓動的。另 外, 由於使用者自己也可以設置計劃任務,所以, Linux 系統也提供了使用者控制計劃任務的命令 :crontab 命令。

crond 是linux下用來週期性的執行某種任務或等待處理某些事件的一個守護進程,與windows下的計劃任務類似,當安裝完成操作系統後,默認會安裝此服務 工具,並且會自動啓動crond進程,crond進程每分鐘會定期檢查是否有要執行的任務,如果有要執行的任務,則自動執行該任務。

crontab命令如下:

root@ubuntu:~# crontab --help
crontab: invalid option -- '-'
crontab: usage error: unrecognized option
usage:  crontab [-u user] file
        crontab [ -u user ] [ -i ] { -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)

Linux下的任務調度分爲兩類,系統任務調度和用戶任務調度。系統任務調度:系統週期性所要執行的工作,比如寫緩存數據到硬盤、日誌清理等。在/etc目錄下有一個crontab文件,這個就是系統任務調度的配置文件。/etc/crontab文件包括下面幾行:

root@ubuntu:~# cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

前兩行是用來配置crond任務運行的環境變量:

  • 第一行shell變量指定了系統要使用哪個shell,這是bash
  • 第二行path變量指定了系統執行命令的路徑!

我們可以新建一個配置文件config.txt,然後使用它:

crontab config.txt

用戶所建立的crontab配置文件中,每一行都代表一項任務。每行的每一列代表一項設置,它的格式共分爲6列,前面1-5列是時間設定列:

  • m: 分鐘(minute),可以是從0到59之間的任何整數。
  • h: 小時(hour),可以是從0到23之間的任何整數。
  • dom: 一個月的第幾天(day of month),可以是從1到31之間的任何整數。
  • mon: 月份(month),可以是從1到12之間的任何整數。
  • dow: 一個星期的第幾天(day of week),可以是從0到7之間的任何整數,這裏的0或7代表星期日。

第6列爲命令。

舉個例子:

0 0 1 * * cat /etc/crontab

這個配置表示,每月1號的0點0分執行cat /etc/crontab命令

時間設定列,除了會出現數字以外,可能還會出現以下內容:

  • 星號(*): 代表所有值,例如mon設置爲*,那麼將表示爲頻率爲每月執行
  • 逗號(,): 代表指定的一些值,例如mon設置爲1,3,5,那麼將表示爲1、3、5月都會執行
  • 連字符(-): 代表指定的值範圍,例如mon設置爲1-3,那麼將表示爲1、2、3月都會執行
  • 正斜線(/): 代表頻率間隔,例如minute設置爲0-30/2,那麼表示爲0-30分內,每兩分鐘執行一次。還可以與星號結合,例如minute設置爲*/2,那麼表示爲每兩分鐘執行

安裝cron服務

apt-get install cron

cron常見命令:

啓動cron服務

service cron start

停止cron服務

service cron stop

重啓cron服務

service cron restart

查看cron服務狀態

service cron status

常見錯誤

ubuntu 在執行crond restart 時提示cron: can’t lock /var/run/crond.pid, otherpid may be 2699: Resource temporarily unavailable

解決辦法:

rm -rf /var/run/crond.pid
/etc/init.d/cron reload
/etc/init.d/cron restart

自此,Over~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章