How To Run A Cron Job Every Second Week?

Published August 19, 2024

Problem: Running Cron Jobs Biweekly

Cron jobs are tasks that run at set times. Setting up a cron job to run every two weeks can be hard, as cron's usual options don't support this timing. You need a custom method to run jobs every two weeks.

Solution: Using Advanced Cron Expressions

Method 1: Using Date Calculations

The date calculation method uses the Unix timestamp to determine if the current week is odd or even. This method lets you run a job every second Tuesday.

Here's the cron expression using the date command:

0 6 * * Tue expr `date +\%s` / 604800 \% 2 >/dev/null || /scripts/fortnightly.sh

Here's what this expression does:

  1. 0 6 * * Tue: Runs the command every Tuesday at 6:00 AM.
  2. expr \date +\%s` / 604800 \% 2`: Calculates if the current week is odd or even.
    • date +\%s: Gets the current Unix timestamp.
    • /604800: Divides by the number of seconds in a week.
    • \% 2: Checks if the result is odd or even.
  3. >/dev/null: Hides the output of the expression.
  4. || /scripts/fortnightly.sh: Runs the script if the expression returns false (0).

Tip: Testing Your Cron Expression

Before implementing your cron job, test the expression to make sure it works as expected. You can use the date command with the -d option to simulate different dates:

date -d "2023-05-02" +%s | xargs -I{} expr {} / 604800 % 2
date -d "2023-05-09" +%s | xargs -I{} expr {} / 604800 % 2

Run these commands for several consecutive Tuesdays to verify the alternating pattern.

Method 2: Using Step Values

Step values in cron let you skip intervals. While not perfect for biweekly schedules, they can be used for approximate solutions.

A cron expression using step values might look like this:

0 6 1-7,15-21 * Tue

This expression runs the job on Tuesdays in the first and third weeks of each month.

Good points of this method:

  • Easy to set up
  • Works with standard cron syntax

Bad points of this method:

  • Not exactly biweekly
  • May run three times in some months
  • Skips some Tuesdays in longer months