Question

Can someone help me in building the cron expression. I've a requirement where I need to run my Job on all the Saturdays at 9:00 AM in a year excluding 1st Saturday of the year.

I had tried with the below expression, but its not working..

0 0 9 ? 1 7#2,7#3,7#4 *, 0 0 9 ?  2-12 SAT *
  • 0 0 9 ? 1 7#2,7#3,7#4 * - It means In the month of January run my job at 9:00 AM on 2nd,3rd,4th Saturdays. But the problem here is it is taking the Last saturday only (i.e. 7#4). In some tutorials I read that comma means it considers all the values but to my surprise it is considering only the last value)

  • 0 0 9 ? 2-12 SAT * - It means from the month of February till December I need to run my job at 9:00 AM.

I need to combine these 2 expressions in such a way it should satisfy my requirement.

Thanks In Advance

Was it helpful?

Solution

You need put compare in your program, not in cronjob. For example, in Unix shell script:

#!/usr/bin/env bash

date=$(date +%a)  
month=$(date +%m)
day=$($date +%e)  

if [ "$date" = "Sat" -a "$month" = "Jan" -a "$day" -lt 8 ];then
  echo "Doesn't run this script at 1st Saturday of the year."
  exit
fi

# put rest script

set the cronjob to run it only at 9am on Saturday

0 9 * * 6 YOUR_PROGRAM

Explanation:

  %a   locale's abbreviated weekday name (e.g., Sun)
  %b   locale's abbreviated month name (e.g., Jan)
  %e   day of month, space padded; same as %_d
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top