Is it possible to put an "if" statement in a user's crontab, or is there another sensible way to organise lots of conditional cron jobs? From the end user's perspective, it would be easiest if they could use the normal crontab and just put their entries between two lines if possible.

Ideally something like:

if [ something ]; then
* * * * * /usr/bin/php /path/to/file.php
0 0 * * * /usr/bin/php /path/to/file2.php
*/5 * * * * /root/script.sh
fi
  • What are the conditions? – Michael Hampton Oct 2 '15 at 10:46
  • It will check whether a hostname resolves to an IP present on the system using dig. The servers are replicas and I'm trying to make sure the crons only run on the current live server. – James Oct 2 '15 at 10:59
up vote 9 down vote accepted

It's not possible to do precisely this.

What you can do however, is to make a script like /usr/local/bin/check_live - which exits with status code 0 if the server is currently live, and nonzero if it's not.

You can then have crontab lines like:

* * * * * /usr/local/bin/check_live && /usr/bin/php /path/to/file.php
0 0 * * * /usr/local/bin/check_live && /usr/bin/php /path/to/file2.php
*/5 * * * * /usr/local/bin/check_live && /root/script.sh
  • A little caveat though, keep in mind that dig doesn't cache responses (which is great if you're looking to get fresh data), but that means that every crontab line with that means one DNS request per line per execution time...) - You might want to do some kind of caching yourself, or use something other than dig that can use the local resolver cache on your box. – Per von Zweigbergk Oct 2 '15 at 17:52
  • I would have done it slightly different. Rather than having the script return a status, I would have it exec "$@" if the conditions were satisfied. Then I would remove the && from the crontab. That's just a matter of taste though, your solution is also fine. – kasperd Oct 19 '15 at 8:41

I wouldn't recommend putting it in crontab file. Instead, create a script where you'll set your conditions and then put it in the crontab file. You'll have a much cleaner and organized setup.

  • 1
    There is not much new in this answer not already found in the accepted answer. – kasperd Oct 19 '15 at 8:43

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.