mac使用launchctl定时运行程序

来源:互联网 发布:2017党章党规网络答题 编辑:程序博客网 时间:2024/06/06 09:22
在linux下可以用crontab来定时执行任务,在mac下可以用launchctl来定时执行任务 

我们使用launchctl来做一个定时执行任务的例子 

首先做一个可执行的脚本,脚本名字叫做: 
run123.sh,脚本的功能就是在/Users/alecyan/Downloads/目录下建一个文件,脚本要改成可执行的权限 
chmod 777 run123.sh 
脚本代码如下: 
Java代码  收藏代码
  1. cd /Users/alecyan/Downloads/  
  2. touch abcabc123.txt  

然后进入到~/Library/LaunchAgents下建一个plist文件,这个就是糸统执行任务时要使用的文件 
文件名叫com.alecyan.testcron.plist 
文件内容如下: 
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  
  3. <plist version="1.0">  
  4. <dict>  
  5.   <key>Label</key>  
  6.   <string>com.alecyan.testcron</string>  
  7.   <key>ProgramArguments</key>  
  8.   <array>  
  9.     <string>/Users/alecyan/Downloads/run123.sh</string>  
  10.   </array>  
  11.   <key>StartCalendarInterval</key>  
  12.   <dict>  
  13.         <key>Minute</key>  
  14.         <integer>4</integer>  
  15.         <key>Hour</key>  
  16.         <integer>13</integer>  
  17.   </dict>  
  18.   <key>StandardOutPath</key>  
  19. <string>/Users/alecyan/Downloads/abc.log</string>  
  20. <key>StandardErrorPath</key>  
  21. <string>/Users/alecyan/Downloads/abcerror.log</string>  
  22. </dict>  
  23. </plist>  
简单的对这里边的内容说明一下,label这里就是给这个任务名个名字,这里一般取plist的文件名,这个名字不能和其它的plist重复。run123.sh就是我们要执行的脚本,StartCalendarInterval里边的参数是说每一天13点4分的时候执行一下脚本。下面脚本表示每86400秒运行一次脚本 

Java代码  收藏代码
  1.   </array>  
  2.   <key>StartInterval</key>
  3.   <dict>  
  4. <integer>86400</integer> 
  5.   </dict>  


然后就可以用下面的几个命令进行操作我们做好的任务了 
Java代码  收藏代码
  1. launchctl load com.alecyan.testcron.plist  
  2. launchctl unload com.alecyan.testcron.plist  
  3. launchctl start com.alecyan.testcron.plist  
  4. launchctl stop com.alecyan.testcron.plist  
  5. launchctl list  

要加载我们做好的plist文件,就是用上面的第一个命令load然,这个时候糸统就会在每天的13点4分执行我们的脚本 
如果想去掉我们的定时任务就可以用unload命令 
如果一个任务今天的13点4分执行过了,然后你改了,com.alecyan.testcron.plist里面的时间,比如说改到14点4分执行,必须unload之后再重新load一下,不然当天不会再执行这个命令 
start可以测试任务,这个是立即执行,不管时间到了没有 
stop可以停止任务 
ok一个简单的定时任务就可以用了 

深入的再说一下,其实,/Library/LaunchAgents这样的目录在mac下一般有三个,我们上面说的是当前用户的目录下的,还有两个一个在/Library/LaunchAgents另一个在/System/Library/LaunchAgents/ 如果是不管哪一个用户都要定时执行的话,就要放在 
/Library/LaunchAgents这个下面 

参考博客: 
http://blog.jeffean.net/blog/2010/08/30/mac-os-shi-yong-launchd-kong-zhi-daemon/ 
http://blog.hebine.com/archives/tag/launchd 
http://nathangrigg.net/2012/07/schedule-jobs-using-launchd/ 
http://www.zhoumingzhi.com/2013/04/05/macos%E7%9A%84launchd%E4%BD%BF%E7%94%A8/ 

https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html这里是plist里的参数的具体说明


转自:http://ylq365.iteye.com/blog/1878917

0 0
原创粉丝点击