How To Run A Cron Job Every 15 Minutes Between Certain Hours?

Published September 4, 2024

Problem: Scheduling Cron Jobs at Specific Intervals

Cron jobs are automated tasks that run at set times. Setting up a cron job to run every 15 minutes within a specific time frame can be tricky. This needs a precise setup to make the task run at the right intervals and only during the chosen hours.

Solution: Configuring the Cron Job

Creating the Correct Cron Expression

To set up a cron job that runs every 15 minutes within specific hours, you need to use the right cron syntax. The cron expression for 15-minute intervals is */15 in the minutes field. This tells the system to run the job every 15 minutes.

To set the hour range for execution, you specify the start and end hours in the hours field. For example, 07-19 would run the job between 7 AM and 7 PM.

Example Cron Job Command

Here's an example of a cron job command that runs every 15 minutes between 7 AM and 7 PM:

*/15 07-19 * * * /path/to/your/script

Each part of this cron expression means:

  1. */15: Runs the job every 15 minutes.
  2. 07-19: Sets the hour range from 7 AM to 7 PM.
      • *: Represents the day of the month, month, and day of the week. The asterisks mean the job will run every day.
  3. /path/to/your/script: The path to the script or command you want to run.

This setup will run your script or command every 15 minutes, starting at 7:00 AM and ending at 7:45 PM each day.

Tip: Testing Your Cron Job

Before setting up your cron job permanently, it's a good idea to test it. You can use the crontab -e command to edit your crontab file, and add the line:

*/15 07-19 * * * /path/to/your/script >> /path/to/logfile.log 2>&1

This will run your script and output any results or errors to a log file. Check the log file after a few intervals to make sure your job is running as expected.