how to not run a cron job between certain datetimes

Say, I have a cron job entry and do want the job to run between 2013-02-01 9PM (Feb 1st 2013) and 2013-02-02 11AM (Feb 2nd 2013), this is one possible solution (in crontab).

* * * * * [ $(/bin/date "+\%Y\%m\%d\%H") -lt 2013020109 -o $(/bin/date "+\%Y\%m\%d\%H") -gt 2013020211 ] && /PATHTOMYSCRIPT/myscript

SSMTP, Crontab gotchas

I had a few cron entries that did not run and for a long a time I had no idea why.

I had the MAILTO variable set at the top of the crontab and I was expecting to be mailed the output of the cron entries. I was surprised when that did not happen. Looking at the mail.err log I came to know that my ssmtp setup was not working as I could see a few entries like this:

Jan 19 09:48:52 localhost sSMTP[22760]: RCPT TO:<testing ssmtp setup@> (553 5.1.2 or other punctuation after the recipient's email address. o1sm8676654wfl.14)

I had gmail setup using ssmtp and the settings seemed to be right. After doing some research I decided to install the ‘mailx’ package and that solved the mail issue and I started receiving the errors from the crontab.

The errors were indicating that the commands in the crontab had a few syntax errors but, they ran fine when I copied and pasted them into my shell and hit enter. After some trial and error I figured out the piece of code that was triggering the error to be something like this:

$(date +'%y%m%d')

I immediately put those into a shell script and used that in the crontab. That did the trick and my cron jobs were running smoothly. I was not too happy with the solution and continued investigating. One of the error messages:

/bin/sh: Syntax error: EOF in backquote substitution

led me to a solution. It turns out that ‘%’ character in my crontab entry was the source of trouble and it had to be escaped as mentioned in the manpage:

Percent-signs (%) in the command, unless
escaped with backslash (), will be changed into newline characters, and
all data after the first % will be sent to the command as standard input.

So, my modified command looked like this:

$(date +'%y%m%d')

And all was good from there.

Also, please remember to save and quit the editor used to edit crontab entries for the new/updated entries to be installed(that’s what happened when my editor was vim).