Get launchd to run task when network connects or reconnects

本小妞迷上赌 提交于 2020-08-20 12:23:30

问题


I run a custom python script to update various dynamic DNS servers through launchctl and it runs every 15 minutes. This is both overkill and underkill.

It would be nice if the script would execute only when reachability changes, and then as a fallback maybe every 30 minutes. I could easily enough update the Python script to check if the external address has changed before calling the update, but if my connection goes down and comes back up with a different IP address, I wouldn't want to have to wait 15-30 minutes.

Note this is different than the keep alive parameter. Odds are my computer will never lose its network connection. It's on a LAN and everything has backup power. So, only Internet reachability matters.


回答1:


I don't think launchd has any built-in trigger for the network coming up, but you can monitor file paths for changes. So if we can find a file that is updated when the network connects, we can implement the desired functionality.

One such file is /var/run/resolv.conf - this file is written whenever the computer renews a DHCP lease. It will be updated when you first connect, and periodically as the DHCP lease is renewed (the timing is set by the DHCP server).

Here is an example launchd plist file.

<?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>org.example.on-dhcp-renew</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/darrin/bin/on-dhcp-renew.sh</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/var/run/resolv.conf</string>
    </array>
</dict>
</plist>

This will only work if you use DHCP addressing for your LAN - as the DHCP client is the program that updates your resolv.conf file.



来源:https://stackoverflow.com/questions/30157288/get-launchd-to-run-task-when-network-connects-or-reconnects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!