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'd like to schedule a task to be run a number of seconds, minutes, hours, days or weeks before a specified day of a week in a particular month. Examples would be:

  • at 8am, 7 days before the last Tuesday of every month
  • at 10am, 11 days before the 2nd Saturday of every month
  • at 6pm, 3 days before the last Friday of every month

I'm comfortable setting up cron/at to run jobs on specified days, and realise that if I wanted to run on these kinds of schedules, I'm probably going to have to run a script in conjunction with cron.

Does anyone have an examples of how I could go about doing this?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

For your first example, 8am 7 days before the last Tuesday of the month, I'd do this:

0 8 * * 2 [[ $(date +%m) -eq $(date -d +7days +%m) ]] && [[ $(date +%m) -ne $(date -d +14days +%m) ]] && myscript

What that does is run at 8am every Tuesday (0 8 * * 2), and then say "if the month 7 days from now is the same as this month" (i.e., this is not the last Tuesday of the month) and "if the month 14 days from now is not the same as this month" (i.e., this is the second-last Tuesday of the month), then run myscript.

This could technically be more efficient -- for example, you know that the second-last Tuesday of the month can't be the 1st of the month -- but that just makes it harder to understand. :) Also, depending on exactly which shell cron runs as and so on, there might be some quoting required (+%m might need to be "+%m") or you might need to escape the percent sign (i.e. +%m might need to be +\%m).

Generalising this trick to other days and advance combinations is left as an exercise for the reader.

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.