These forums are read-only!
Restricting cron job to a specific host
  • I've got a bunch of slices doing similar work, and one of them runs an hourly cron task that must only be run on one server in the cluster.

    I'd like to set up something foolproof so that, if I clone the cronning slice, the cron task will not run on the clone, by default. So, I've been trying stuff like this in my crontab;

    0 * * * * [ `/bin/hostname` == "myserver" ] && /usr/local/bin/my_task

    and;

    0 * * * * if [ `/bin/hostname` == "myserver" ]; then /usr/local/bin/my_task; fi

    Both variants work fine on the command line, but neither works when run via cron - the task doesn't get run, and there's nothing in syslog other than that the cron script was triggered at the appropriate time.

    Does anyone know if/how this can be done in crontab? I'd rather not edit the task itself to check the hostname, but that's my fallback if I can't get this to work.

    Thanks in advance

    David
  • You could try setting the SHELL variable in your crontab - insert a line like this:
    SHELL="/bin/bash" although I'm not sure if that would work since I think it should already be using your default shell to execute the cron tasks. If that doesn't work, though, try changing the cron line to this:
    0 * * * * /bin/bash -c '[ `/bin/hostname` == "myserver" ] && /usr/local/bin/mytask' which will cause bash to execute the command specified as the argument to -c. Alternatively, you could create a wrapper script, something like
    #!/bin/bash
    [ `/bin/hostname` == "myserver" ] && /usr/local/bin/mytask
    and put the path to that file in your crontab.

    :) David
  • Thanks, David. The 'bash -c' trick worked perfectly.