mac 定时任务

Posted on Posted in mac

mac下的定时任务,crontab 是好使的,但是不推荐,推荐plist

plist 官方说明

  1. 新建定时脚本
vim autoBash.sh
#!/bin/bash
python autoExe.py

chmod +x autoBash.sh
  1. 新建plist
cd ~/Library/LaunchAgents

vim com.pyExe.launchctl.plist

<?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.aigo.launchctl.plist</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/liuhonghe/autoBash.sh</string>
  </array>
  <key>StartCalendarInterval</key>
  <dict>
        <key>Minute</key> # 每天12点4分执行
        <integer>4</integer>
        <key>Hour</key>
        <integer>12</integer>
  </dict>
  <key>StandardOutPath</key>
<string>/Users/liuhonghe/autoBash.log</string> # log
<key>StandardErrorPath</key>
<string>/Users/liuhonghe/autoBash.err</string> # err
</dict>
</plist>
  1. 加载
launchctl load   com.pyExe.launchctl.plist # 启动脚本
launchctl unload com.pyExe.launchctl.plist # 停止脚本
launchctl start  com.pyExe.launchctl.plist
launchctl stop   com.pyExe.launchctl.plist
launchctl list
  • 要让任务生效,必须先load命令加载这个plist
  • 如果任务呗修改了,那么必须先unload,然后重新load
  • start可以测试任务,这个是立即执行,不管时间到了没有
  • 执行start和unload前,任务必须先load过,否则报错
  • stop可以停止任务
  • ProgramArguments内不能直接写命令,只能通过shell脚本来执行
  1. 其他例子
<?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.pyExe.launchctl.plist</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/pyExe/autoBash.sh</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>StartInterval</key>
    <integer>30</integer> # 每个30秒执行
</dict>
</plist>
» 转载请注明来源:若我若鱼 » mac 定时任务

Leave a Reply

Your email address will not be published. Required fields are marked *

nine − eight =