1

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
10

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
| improve this answer | |
  • 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
  • Exactly the sort of thing I was looking for. As an addendum, on my old server setup of two servers, only one of which was running the site database at any time, you could easily get cron jobs to run on only the server that was currently hosting mysql by using this: 33 11 * * * [ -f /var/lib/mysql/ibdata1 ] && php /path-to-script/script.php > /dev/null ...which saves you the trouble of writing a bash script, if you can depend on a file being present on only the server you want to execute the cron job on. – dartacus Nov 12 '19 at 8:45
0

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.

| improve this answer | |
  • 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 agree to our terms of service, privacy policy and cookie policy

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