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?
For your first example, 8am 7 days before the last Tuesday of the month, I'd do this:
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 runmyscript
.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.