Mac 使用 launchctl 定时运行程序

在linux下能够用crontab来定时执行任务,在MAC下能够用launchctl来定时执行任务。 html

咱们使用launchctl来作一个定时执行任务的例子。 linux

首先作一个可执行的脚本,脚本名字叫作:AutoMakeLog.sh,脚本的功能就是在/Users/jackin/Downloads/目录下建一个日志文件。 shell

Shell文件/Users/jackin/AutoMakeLog.sh: app

cd /Users/jackin/Downloads/
LOG=`date +"%Y-%m-%d %H:%M:%S"`
LOGFILE=`date +"date-log-%Y%m%d.log"`
echo $LOG > $LOGFILE

脚本要改为可执行的权限 测试

chmod 777 AutoMakeLog.sh

而后进入到~/Library/LaunchAgents下建一个plist文件,这个就是糸统执行任务时要使用的文件 日志

文件名叫com.jackin.launchctl.plist,文件内容以下: code

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.jackin.launchctl.plist</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/jackin/AutoMakeLog.sh</string>
  </array>
  <key>StartCalendarInterval</key>
  <dict>
  		<key>Minute</key>
		<integer>4</integer>
  		<key>Hour</key>
		<integer>13</integer>
  </dict>
  <key>StandardOutPath</key>
<string>/var/log/AutoMakeLog.log</string>
<key>StandardErrorPath</key>
<string>/var/log/AutoMakeLog.err</string>
</dict>
</plist>

简单的对这里边的内容说明一下,label这里就是给这个任务名个名字,这里通常取plist的文件名,这个名字不能和其它的plist重复。AutoMakeLog.sh就是咱们要执行的脚本,StartCalendarInterval里边的参数是说每一天13点4分的时候执行一下脚本。 xml

而后就能够用下面的几个命令进行操做咱们作好的任务了。 htm

launchctl load   com.jackin.launchctl.plist
launchctl unload com.jackin.launchctl.plist
launchctl start  com.jackin.launchctl.plist
launchctl stop   com.jackin.launchctl.plist
launchctl list

要加载咱们作好的plist文件,就是用上面的第一个命令load然,这个时候糸统就会在天天的13点4分执行咱们的脚本。若是想去掉咱们的定时任务就能够用unload命令。 crontab

若是一个任务今天的13点4分执行过了,而后你改了,com.jackin.launchctl.plist里面的时间,好比说改到14点4分执行,必须unload以后再从新load一下,否则当天不会再执行这个命令。

start能够测试任务,这个是当即执行,无论时间到了没有

stop能够中止任务

深刻的再说一下,其实,/Library/LaunchAgents这样的目录在MAC下通常有三个,咱们上面说的是当前用户的目录下的,还有两个一个在/Library/LaunchAgents另外一个在/System/Library/LaunchAgents/。若是是无论哪个用户都要定时执行的话,就要放在 /Library/LaunchAgents这个下面 。

launchd.plist 文件的详细说明https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html

相关文章
相关标签/搜索