网络连接或重新连接时启动运行任务 [英] Get launchd to run task when network connects or reconnects

查看:51
本文介绍了网络连接或重新连接时启动运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行一个自定义python脚本,以通过launchctl更新各种动态DNS服务器,它每15分钟运行一次.这既是滥杀滥伤,又是倒杀.

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.

如果脚本仅在可访问性发生变化时才执行,然后每30分钟作为一次备用,则会很好.我可以很容易地更新Python脚本,以在调用更新之前检查外部地址是否已更改,但是如果我的连接断开并返回了另一个IP地址,我就不必等待15-30分钟

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.

请注意,这与keep alive参数不同.奇怪的是,我的计算机永远不会失去其网络连接.它在局域网上,所有东西都有备用电源.因此,只有Internet可达性很重要.

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.

推荐答案

我认为launchd不会为即将到来的网络提供任何内置触发器,但是您可以监视文件路径的更改.因此,如果我们找到一个在网络连接时更新的文件,就可以实现所需的功能.

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.

一个这样的文件是/var/run/resolv.conf-每当计算机续订DHCP租约时都会写入此文件.第一次连接时,它将更新,并且随着DHCP租约的更新而定期更新(时间由DHCP服务器设置).

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).

这是一个 launchd plist 文件的示例.

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>

这仅在您为LAN使用DHCP寻址时才有效-因为DHCP客户端是更新resolv.conf文件的程序.

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.

这篇关于网络连接或重新连接时启动运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆