To create a cron expression that runs at 3 AM every other Tuesday, we need to carefully calculate the days. Cron doesn't natively support "every other Tuesday" directly in a simple expression, so we typically work around this limitation by specifying the exact days of the month this would occur or by using additional scripts or conditions to check weeks. Here, I'll give you an example using a basic cron expression set to trigger every Tuesday, and then explain how you might manually calculate specific Tuesdays if you want to strictly limit it to "every other Tuesday."
The basic cron format is:
MIN HOUR DAY_OF_MONTH MONTH DAY_OF_WEEK COMMAND
To run a command every Tuesday at 3 AM, you would use:
0 3 * * 2 COMMAND
This breaks down as:
0
minutes past the hour3
AM*
any day of the month*
any month2
day of the week (where Sunday=0, Monday=1, Tuesday=2, etc.)
To specifically configure "every other Tuesday," we need to do some manual calculations or use external logic, because cron syntax does not directly support this kind of complex scheduling. Here’s a general approach using additional shell logic:
0 3 * * 2 [ $((\$(date +\%V) \% 2)) -eq 1 ] && COMMAND
This command uses:
date +%V
gives the ISO week number.\%V \% 2
calculates if the week is odd or even.-eq 1
ensures the command only runs on odd weeks (you can switch to-eq 0
for even weeks).
However, note this relies on the first week of the year being an odd week, and will alternate from there. If the year starts on the first few days being a Tuesday on an even week, you may need to adjust the logic accordingly.
If you prefer not to use additional scripts or conditions and want to use pure cron, consider manually setting the days for "every other Tuesday" based on the calendar for each specific year. For example, if in a given month Tuesdays fall on the 1st, 8th, 15th, 22nd, and 29th, and you want to start from the 1st, your cron expression would be:
0 3 1,15 * * COMMAND # Runs on the 1st and 15th if those are Tuesdays
You will need to adjust this manually every year or several months as needed, depending on the specific dates of Tuesdays in each month.
For a fully automated and error-free setup without manually setting dates, using a small script as part of the cron job is the most robust method. This allows the cron syntax to stay clean while handling the complex schedule logic externally.