Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I want to run some jobs on day 1 of each month and others on day 1 of each week, but what if both collide? In this case the month should have precedence. How do I tell this cron?

# run on every day 1 of each month:
59 12 1 * * user script_month

# run on every day 1 of each week:
59 12 * * 1 user script_week

EDIT 1:

There is an answer that uses "IF" which is a good workaround.

What about this:

# run on every day 1 of each week:
59 12 2-31 * 1 user script_week

Maybe it also does what I am asking for? (run on all weeks on day 1 except if it is day 1 of the month)

Edit 2:

I found this:

"If both [date] fields are restricted (i.e., aren't *), the command will be run when either field matches the current time." (source: http://thewatertower.org.uk/news/000160/crontab_the_first_five_fields_combine_to_restrict_the_schedule_except_for_when_they_dont.html )

Seems it is not possible like I wrote in Edit 1?

share|improve this question
    
It is not correct that non-* entries match if for any match of the fields, the run if all of them match. For example "0 0 * * " runs at exactly midnight, not for every minute between 00:00-00:59 *OR on the hour for every hour 00 through 23. –  Sean Reifschneider Dec 7 '10 at 3:58

2 Answers 2

up vote 6 down vote accepted

Have script_week check whether it is running on day 1 of the month. If it is, then have it exit before doing any real work. For example, in a bash script, such a check might look like this:

if [ `/bin/date +%d` = "01" ]; then exit 0; fi

If you prefer, you could leave script_week unmodified, and instead put a similar check into the crontab entry for script_week, something like this:

59 12 * * 1 user if [ `/bin/date +\%d` != "01" ]; then script_week; fi
share|improve this answer

If it is a long running job, you could also consider having the script use a lock-file so that only one instance of it will run at a time. Then you could have it listed in both cron entries, and rely on it detecting when one is already running.

This can also be useful if it's a VERY long running job. Sometimes I've run across cron jobs that usually don't take very long, but if the system is running under a high load processing logs or a big job, it might take longer than expected. Then if multiple of these jobs start at the same time, they can start stacking up and eventually bring the machine to it's knees.

Unlikely for a job that runs once a week, but it is a good habit to get into -- preventing jobs from stacking up, and it would do double duty to prevent the job from being run from both crontab entries.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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