When working with cron jobs, you can use specific patterns in the minute field to achieve odd/even execution:
# Odd minutes (1,3,5,...,59) 1-59/2 * * * * /path/to/odd-minute-script.sh # Even minutes (0,2,4,...,58) 0-58/2 * * * * /path/to/even-minute-script.sh
For better readability and maintenance, consider these alternatives:
# Using comma-separated values (odd minutes) 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59 * * * * /path/to/odd-job # Using step values (preferred method) */2 * * * * /path/to/even-job # Runs at :00, :02, ..., :58 1-59/2 * * * * /path/to/odd-job # Runs at :01, :03, ..., :59
To test your cron jobs before deploying:
# Check next execution times crontab -l | grep -v "^#" | while read -r line; do echo "Next run times for: $line" for i in {1..5}; do echo -n "$i. " echo "$line" | awk '{print $1" "$2" "$3" "$4" "$5}' | xargs -I {} date -d "now + {}" "+%Y-%m-%d %H:%M:%S" done done
Here's a complete example for monitoring system resources:
# Even minute job - system monitoring 0-58/2 * * * * /usr/bin/printf "EVEN MINUTE: $(date) - CPU: $(grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}')" >> /var/log/system_mon.log # Odd minute job - cleanup task 1-59/2 * * * * find /tmp -type f -mmin +60 -delete
- Ensure your system's cron daemon supports the step syntax (most modern systems do)
- Account for potential job overlap if tasks run longer than 1 minute
- Consider using flock for preventing concurrent execution
- Test thoroughly in non-production environments first
When working with cron jobs, sometimes we need more granular control than the standard */2 minute interval. The requirement here is to have:
- Job A: Runs at every odd minute (1,3,5,...,59)
- Job B: Runs at every even minute (0,2,4,...,58)
The most straightforward way to achieve this is by using step values and ranges in your crontab:
# For odd minutes (1-59, stepping by 2) 1-59/2 * * * * /path/to/odd_job.sh # For even minutes (0-58, stepping by 2) 0-58/2 * * * * /path/to/even_job.sh
If you prefer a different approach, you can also use comma-separated values for even minutes:
# For even minutes 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 * * * * /path/to/even_job.sh
However, the first method is more maintainable and easier to understand.
After setting up your cron jobs, you can verify them using:
crontab -l
To test the timing pattern without waiting, you can use tools like:
# For testing the odd minute job for i in {1..59..2}; do echo "Testing minute $i"; /path/to/odd_job.sh; done
This alternating cron pattern is useful for:
- Load balancing between two processes
- Implementing round-robin processing
- Running maintenance tasks in staggered intervals
- A/B testing scheduled jobs