mac系统创建plist执行定时任务

在linux下执行定期任务可以使用crontab,目前mac os也可以使用它,不过已不推荐使用。推荐做法是采用plist脚本,plist脚本可以设置执行的动作,时间间隔等其他一些信息。另外crontab的最小时间间隔是一分钟,使用plist脚本原则上时间间隔可以为一秒。

plist脚本存放路径为/Library/LaunchDaemons或/Library/LaunchAgents,其区别是后一个路径的脚本当用户登陆系统后才会被执行,前一个只要系统启动了,哪怕用户不登陆系统也会被执行。

可以通过两种方式来设置脚本的执行时间。一个是使用StartInterval,它指定脚本每间隔多长时间(单位:秒)执行一次;另外一个使用StartCalendarInterval,它可以指定脚本在多少分钟、小时、天、星期几、月时间上执行,类似如crontab的中的设置。

<?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.yangyz.cron.test.plist</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/yangyz/plist-test.sh</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>StartInterval</key>
    <integer>60</integer>
</dict>
</plist>

launchctl命令可以控制plist脚本停止或重新加载。例如:
停止脚本com.yangyz.cron.test.plist运行
launchctl unload /Library/LaunchDaemons/com.yangyz.cron.test.plist

启动脚本com.yangyz.cron.test.plist运行
launchctl load /Library/LaunchDaemons/com.yangyz.cron.test.plist

参考资料:
http://www.devdaily.com/mac-os-x/launchd-plist-examples-startinterval-startcalendarinterval
http://www.devdaily.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs

猜你喜欢

转载自linwwwei.iteye.com/blog/2150029
今日推荐