在 Mac OSMac\ OSMac OS 上处理周期执行的任务一般用 croncroncron 来搞,croncroncron 会读取一个或者多个包含定时任务的配置文件——"crontab""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
执行该命令后会进入编辑器,修改 crontabcrontabcrontab 文件,不存在会自动创建,首次使用会提示选择编辑器,然后在末尾加入定时任务的相关信息,退出保存即可。例如添加:
15 10 * * * your/script/path
意为在每天十点十五执行 /your/script/path/your/script/path/your/script/path。
作业格式
croncroncron 的定时任务作业的相关信息有一个固定的格式:
{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script}
一共六个字段信息,
minuteminuteminute 取值范围 0∼590 \sim 590∼59,
hourhourhour 取值范围 0∼230 \sim 230∼23,
day−of−monthday-of-monthday−of−month 取值范围 1∼311 \sim 311∼31,
monthmonthmonth 取值范围 1∼121 \sim 121∼12,
day−of−weekday-of-weekday−of−week 取值范围 0∼70 \sim 70∼7,周日可以是 0 or 70\ or\ 70 or 7,
full−path−to−shell−scriptfull-path-to-shell-scriptfull−path−to−shell−script 是要执行的脚本。
查看作业
crontab -l
显示 crontabcrontabcrontab 文件,可以查看当前所有定时任务作业信息。
删除作业
crontab -r
可以删除 crontabcrontabcrontab 文件,删除后,所有定时任务都被删除,如果想要删除个别定时任务,可以选择 −e-e−e 编辑 crontabcrontabcrontab 文件进行删除对应的任务。
crontab -lr
删除 crontabcrontabcrontab 文件并提醒用户。
示例
每分钟执行
* * * * * script
每小时 151515 分钟和 454545 分钟执行
15, 45 * * * * script
每天上午 8∼118 \sim 118∼11 点的 151515 和 454545 分钟执行
15, 45 8-11 * * * script
每隔一天上午 8:158:158:15 执行
15 8 */2 * * script
每周一早上 10:1510:1510:15 执行
15 10 * * 1 script
每月 111 号 10:1510:1510:15 执行
15 10 1 * * script