网络启动时如何运行cron作业?

Dim*_*ima 6 crontab cron-jobs cron

我有一些每天运行的 anacron 工作。脚本更新本地 bzr 和 git 存储库。当然,这些脚本需要有效的网络连接。我在笔记本电脑上,有线和无线互联网通常不够快。这会导致我的 cron 作业在拉存储库时超时 =(

所以:

如何在运行特定的 cron 作业之前确保互联网已启动?或者,如果没有网络,如何使作业失败,以便 anacron 稍后再次重试?

vav*_*ava 8

我认为您可以使用Upstart来帮助您。请注意,我还没有测试过下面的代码是否有效,但应该有一些非常相似的东西。

# /etc/init/update-repositories.conf - Update local repos
#

description     "Update local repos"

# this will run the script section every time network is up
start on (net-device-up IFACE!=lo)

task

script
    svn up && git fetch
#   do some other useful stuff
end script
Run Code Online (Sandbox Code Playgroud)

差不多吧。您可能想要添加一些代码来检查它是否不经常运行。您可能还想添加start update-repositories到您的 crontab 中,如果您长时间上网,它会确保您的更新会发生。


Mar*_*ppi 6

我制作了一个 cron,它在 DNS 服务器上进行了 ping 测试以确保网络连接。像这样的东西:

ping 8.8.8.8 -c 1 -i .2 -t 60 > /dev/null 2>&1
ONLINE=$?

if [ ONLINE -eq 0 ]; then
    #We're offline
else
    #We're online
fi
Run Code Online (Sandbox Code Playgroud)

最近我使用了这样的东西:

#!/bin/bash

function check_online
{
    netcat -z -w 5 8.8.8.8 53 && echo 1 || echo 0
}

# Initial check to see if we are online
IS_ONLINE=check_online
# How many times we should check if we're online - this prevents infinite looping
MAX_CHECKS=5
# Initial starting value for checks
CHECKS=0

# Loop while we're not online.
while [ $IS_ONLINE -eq 0 ]; do
    # We're offline. Sleep for a bit, then check again

    sleep 10;
    IS_ONLINE=check_online

    CHECKS=$[ $CHECKS + 1 ]
    if [ $CHECKS -gt $MAX_CHECKS ]; then
        break
    fi
done

if [ $IS_ONLINE -eq 0 ]; then
    # We never were able to get online. Kill script.
    exit 1
fi

# Now we enter our normal code here. The above was just for online checking
Run Code Online (Sandbox Code Playgroud)

这不是最优雅的 - 我不知道如何通过系统上的简单命令或文件进行检查,但这在需要时对我有用。