How To Specify Odd Values In Crontab?

Published August 20, 2024

Problem: Specifying Odd Values in Crontab

Crontab is a tool for scheduling tasks, but it can be difficult when setting up jobs that run on odd-numbered intervals. The standard crontab syntax doesn't have a way to directly specify odd values, which can make scheduling certain tasks more complex.

Solutions for Setting Odd-Numbered Cron Jobs

Using Range with Step Values

The range with step values method is a way to schedule odd-numbered cron jobs. The syntax for this approach is 1-23/2. This format tells crontab to start at 1, go up to 23, and increment by 2 each time. It covers all odd numbers within that range.

For hours, you would use 1-23/2 to run a job at 1 AM, 3 AM, 5 AM, and so on until 11 PM. For minutes, 1-59/2 would run the job at odd-numbered minutes throughout the hour. This method works for other time units like days or months.

Example: Odd-Numbered Daily Cron Job

# Run a script at 1:30 AM on odd-numbered days of the month
30 1 1-31/2 * * /path/to/your/script.sh

Explicit Listing Method

Another option is to write out all the odd numbers. For example, to run a job at odd hours, you would use:

1,3,5,7,9,11,13,15,17,19,21,23

This method works across different cron implementations. You can easily see what the schedule will be.

However, this approach has drawbacks. It can make your crontab file longer and harder to maintain, especially for larger ranges. It's also more likely to have typing errors when inputting the numbers manually.

Tip: Verify Your Cron Syntax

Always double-check your cron syntax using online cron expression validators or your system's crontab command with the -l flag to list and verify your entries.