How to schedule a job that depends on network availability?
Use anacron
, because you won't be up 24/7, then add some magic to ensure the network is up (by pinging the default gateway), and if not delay the execution.
Here's an example script that will get you close:
#!/bin/bash
cd repo
JOB="git pull"
ping -c 2 $(netstat -rn | awk '/^0.0.0.0/ {print $2}') 2>&1 > /dev/null && $JOB || echo $JOB | at $(date --date="+1 hour" +%H:%M)
Run the job when you connect to the network. Most distributions have a scripting infrastructure that you can plug into, though you will need root permissions. If you connect with NetworkManager or Wicd, they have their own hook infrastructure as well. Add a cron job that only runs if the network is available (and, optionally, only if the job hasn't been run performed in a long time), in case the network remains connected for a long time.
You don't specify your distribution, so I'll give an example for a Debian-based distribution. The scripts in /etc/network/if-up.d
are executed after an interface is brought up; see the interfaces(5)
man page for more information. Write a script /etc/network/if-up.d/zzzz_balki_git_pull
such as this:
#!/bin/sh
su balki -c /home/balki/bin/pull_repository_if_old
with a pull_repository_if_old
that does something like this (run git pull
if the network is available unless there is a timestamp that is less than 7 days old):
#!/bin/sh
set -e
if [ -z "$(find /path/to/.repository.pull.timestamp -mtime -7)" ] &&
ping -c 1 -w 1 repository.example.com >/dev/null 2>/dev/null
then
cd /path/to/repository
git pull
touch /path/to/.repository.pull.timestamp
fi
EOF
And a crontab entry on your account:
28 4 * * * /home/balki/bin/pull_repository_if_old