M a c   O S Mac\ OS Mac OS 上处理周期执行的任务一般用 c r o n cron cron 来搞, c r o n cron cron 会读取一个或者多个包含定时任务的配置文件—— " c r o n t a b " "crontab" "crontab"

cron 服务

service crond start		# 启动服务
service crond stop		# 关闭服务
service crond restart	# 重启服务
service crond reload	# 重新载入配置
service crond status	# 查看服务状态

配置文件

/var/spool/cron/	# 所有用户 cron 任务
/etc/crontab/		# 系统管理员制定的 cron 任务
/etc/cron.d/		# 需要执行的 cron 脚本文件

添加作业

crontab -e

执行该命令后会进入编辑器,修改 c r o n t a b crontab crontab 文件,不存在会自动创建,首次使用会提示选择编辑器,然后在末尾加入定时任务的相关信息,退出保存即可。例如添加:

15 10 * * * your/script/path

意为在每天十点十五执行 / y o u r / s c r i p t / p a t h /your/script/path /your/script/path

作业格式

c r o n cron cron 的定时任务作业的相关信息有一个固定的格式:

{
   minute} {
   hour} {
   day-of-month} {
   month} {
   day-of-week} {
   full-path-to-shell-script}

一共六个字段信息,
m i n u t e minute minute 取值范围 0 ∼ 59 0 \sim 59 059
h o u r hour hour 取值范围 0 ∼ 23 0 \sim 23 023
d a y − o f − m o n t h day-of-month dayofmonth 取值范围 1 ∼ 31 1 \sim 31 131
m o n t h month month 取值范围 1 ∼ 12 1 \sim 12 112
d a y − o f − w e e k day-of-week dayofweek 取值范围 0 ∼ 7 0 \sim 7 07,周日可以是 0 &nbs***bsp; 7 0\ or\ 7 0 or 7
f u l l − p a t h − t o − s h e l l − s c r i p t full-path-to-shell-script fullpathtoshellscript 是要执行的脚本。

查看作业

crontab -l

显示 c r o n t a b crontab crontab 文件,可以查看当前所有定时任务作业信息。

删除作业

crontab -r

可以删除 c r o n t a b crontab crontab 文件,删除后,所有定时任务都被删除,如果想要删除个别定时任务,可以选择 − e -e e 编辑 c r o n t a b crontab crontab 文件进行删除对应的任务。

crontab -lr

删除 c r o n t a b crontab crontab 文件并提醒用户。

示例

每分钟执行

* * * * * script

每小时 15 15 15 分钟和 45 45 45 分钟执行

15, 45 * * * * script

每天上午 8 ∼ 11 8 \sim 11 811 点的 15 15 15 45 45 45 分钟执行

15, 45 8-11 * * * script

每隔一天上午 8 : 15 8:15 8:15 执行

15 8 */2 * * script

每周一早上 10 : 15 10:15 10:15 执行

15 10 * * 1 script

每月 1 1 1 10 : 15 10:15 10:15 执行

15 10 1 * * script