Cron job explained: Syntax, scheduling, and best use cases

Cron job explained: Syntax, scheduling, and best use cases

A cron job is a time-based scheduler in Unix-like operating systems, such as Linux and macOS. It automates repetitive tasks like backups, system maintenance, and script execution.

Users define a schedule and command in a crontab file to keep critical processes running consistently in the background without manual intervention.

To use cron effectively, you need to understand its core components:

  • Syntax and operators. Cron uses five timing fields (minute, hour, day of month, month, and day of week) and special characters, such as asterisks and slashes, to define intervals.
  • Configuration. Users manage schedules with the crontab command or by placing scripts in specific system directories.
  • Permissions. The cron.allow and cron.deny files control access and help maintain system security.
  • Practical application. Common use cases include automating database backups, clearing server caches, and sending periodic email reports.

What is a cron job?

A cron job is a utility that lets Linux and Unix users run commands or scripts automatically at a specified time and date. Instead of running a command manually every day or week, you schedule it once, and the system executes it in the background at the set time.

This automation is important for server management. For example, a system administrator managing a virtual private server (VPS) cannot back up databases manually every night at 3:00 AM.

A cron job handles this task reliably, improving efficiency and reducing human error.

Common cron job use cases include:

  • System maintenance. Deleting temporary files, rotating log files, or clearing cached data to free up disk space.
  • Data management. Dumping MySQL databases to a backup folder or syncing files between remote servers.
  • Notifications. Sending automated email digests, checking for system updates, or monitoring disk usage and alerting admins when space runs low.
  • Web applications. Triggering PHP scripts for tasks such as newsletter distribution or subscription renewals.

How does a cron job work?

A cron job runs through the cron daemon (crond), a background service that runs continuously and executes commands defined in crontab (cron table) files.

Every minute, the daemon checks the configuration files and determines whether any tasks are scheduled to run at that time.

It’s important to distinguish between the two types of configuration files:

  • System crontab. Located at /etc/crontab, this file handles system-wide tasks and only root users can edit it. It includes an extra field that specifies which user runs the command.
  • User crontab. Each user has their own crontab file. The storage location varies by distribution, such as /var/spool/cron/crontabs/ on Debian and Ubuntu, and /var/spool/cron/ on RHEL, CentOS, and Fedora. Users edit these files with the crontab -e command, and the tasks run with that user’s permissions.

Understanding crontab syntax and operators

Crontab syntax defines scheduled tasks (cron jobs) using a single line with five time-and-date fields followed by the command to execute. Special operators add flexibility when you define time intervals.

Here’s the basic format of a crontab entry:

minute hour day_of_month month day_of_week command_to_execute

The five timing fields (minute, hour, date)

The five timing fields define when a cron job runs. The system reads the schedule in the following order:

FieldDescriptionAllowed values
MinuteThe minute of the hour when the command runs.0–59
HourThe hour of the day in 24-hour format.0–23
Day of monthThe specific date of the month.1–31
MonthThe month of the year.1–12 or JAN–DEC
Day of weekThe day of the week.0–6, where Sunday = 0 (or 7 on some systems)

Important! Be careful when scheduling jobs across multiple servers in different time zones. Always check each server’s local time with the date command to confirm your configuration is correct.

Crontab operators

Crontab operators let you define complex intervals and patterns within the timing fields. Cronie and its predecessor, Vixie cron, support the following operators.

These implementations serve as the default cron tools on most Linux distributions, including Ubuntu, Debian, RHEL, CentOS, and Fedora.

  • Asterisk (*). Represents all possible values. For example, an asterisk in the minute field means the job runs every minute.
  • Comma (,). Specifies a list of unique values. For example, 1,5 in the day of week field runs the task on Monday and Friday.
  • Hyphen (-). Defines a range of values. For example, 6-9 in the month field runs the job from June to September.
  • Slash (/). Specifies step values or increments. For example, */12 in the hour field runs the command every 12 hours.

These operators are not supported by standard Linux cron. They work only in Java-based schedulers, such as Quartz and Spring Boot, or cloud services like AWS EventBridge:

  • Last (L). Specifies the last day of the month or the last occurrence of a weekday.
  • Weekday (W). Finds the nearest weekday (Monday–Friday) to a given date.
  • Hash (#). Specifies the nth occurrence of a weekday, such as the second Monday of the month.
  • Question mark (?). Indicates that the day of month or day of week does not matter.

💡 Pro tip

Most cron implementations let you combine ranges with step values. For example, 1-20/2 runs a job every two minutes during the first 20 minutes.

If you’re unsure about manually writing the cron syntax, use free tools like Crontab Generator or Crontab.guru to generate the exact numbers for the time and date of your command.

Cron job examples

The following examples show how to apply crontab syntax to real-world tasks.

Cron syntaxPurposeExplanation
0 0 * * 0 /root/backup.shWeekly backupRuns the backup script every Sunday at midnight.
0 * * * 1 /root/clearcache.shServer maintenanceClears the cache every hour, but only on Mondays.
0 6,18 * * * /root/db-dump.shDatabase snapshotDumps the database twice a day at 6 AM and 6 PM.
*/10 * * * * /scripts/monitor.shUptime monitoringRuns a monitoring script every 10 minutes.
0 0 1,15 * * /scripts/payroll.phpBi-monthly TaskRuns a payroll script on the 1st and 15th of every month at midnight.
30 2 * * * /usr/bin/apt-get updateSystem updateChecks for package updates daily at 2:30 AM, which is usually a low-traffic time.
* * * * /scripts/s1.sh; /scripts/s2.shMultiple tasksRuns multiple commands in a single cron job by separating them with a semicolon.
0 8 1-7 * * [ “$(date ‘+%u’)” = “1” ] && /scripts/report.shMonthly reportGenerates a report at 8 a.m. on days 1–7 of the month, but only executes the script when it’s Monday.

What are cron job special strings?

Special strings are shortcuts that start with @ and replace the five-field syntax. They improve readability for common schedules and reduce the risk of syntax errors.

  • @reboot. Runs the command once when the cron daemon starts.
  • @hourly. Runs once an hour (equivalent to 0 * * * *).
  • @daily (or @midnight). Runs once a day at midnight (equivalent to 0 0 * * *).
  • @weekly. Runs once a week on Sunday at midnight (equivalent to 0 0 * * 0).
  • @monthly. Runs once a month on the 1st at midnight (equivalent to 0 0 1 * *).
  • @yearly (or @annually). Runs once a year on January 1st (equivalent to 0 0 1 1 *).

Here are a few examples of cron jobs using special strings:

@daily /home/user/scripts/daily-cleanup.sh
@reboot /usr/local/bin/start-my-app.sh
@hourly /var/www/html/monitor.php

Important! The @reboot directive runs when the cron daemon starts, not necessarily when the system boots. If you stop and restart the cron service without rebooting the system, @reboot jobs run again.

Cron permissions

System administrators control who can schedule cron jobs using two files in the /etc/ directory: cron.allow and cron.deny.

  • cron.allow. If this file exists, only the users listed in it can create, edit, or run cron jobs. The system blocks all other users.
  • cron.deny. If cron.allow doesn’t exist, the system checks this file instead. Users listed here cannot use cron, while all other users can.

If neither file exists, the default behavior depends on the distribution:

  • Debian and Ubuntu. All users can use cron by default.
  • RHEL, CentOS, and Fedora. Only root can use cron by default.

Always check your distribution’s documentation or test cron access with a non-root user.

For example, to allow only a database administrator (dbadmin) to schedule tasks, create a cron.allow file and add dbadmin to it. This setup prevents other users from running unauthorized background tasks that consume system resources.

How to set up a cron job

To set up a cron job, open your machine’s terminal, confirm that cron is installed, create or edit a crontab file with crontab -e, and view your scheduled tasks with crontab -l.

For some jobs, you may need elevated or root privileges, or you may need to place scripts in system directories for recurring tasks.

1. Access the terminal or SSH

To manage cron jobs, access your server’s command line. If you use a remote server or VPS, connect through SSH with a client such as PuTTY on Windows or Terminal on macOS or Linux.

Alternatively, Hostinger VPS users can use the browser terminal feature available in the VPS dashboard of hPanel.

2. Install cron

Cron is commonly pre-installed by default in all Linux distributions. Otherwise, run the installation command according to your package manager. Here’s the command for Ubuntu with apt:

sudo apt install cron

Before proceeding with the basic cron job operations, you must understand the configuration files – the system crontab and user crontab.

The system crontab is used to schedule system-wide essential jobs that are only editable by those with root privileges. Meanwhile, leverage the user crontab to create and edit jobs that only apply at the user level.

To edit the system crontab, ensure the current user has root privileges. Read on to learn several basic operations that cron can perform.

A basic cron job operation

Using a Cron Job to Create a Crontab File

Enter the snippet below into the command line to edit an existing crontab file. If your system doesn’t have it, the command will automatically create a new one.

crontab -e

When entering crontab -e for the first time, it will ask you to choose which text editor you want to edit the file with, such as nano or vi. In the text editor, you can add other commands or edit existing ones.

Using Cron Job to Display a List of Active Scheduled Tasks

To see a list of active, scheduled tasks in your system, enter the following command:

crontab -l

If your system has multiple users, you can view their crontab file lists by entering the command below as a superuser:

crontab -u username -l

Using Cron Jobs to Grant Yourself Root Access

Due to user privilege restrictions, some commands can only run using root permissions. To give yourself root privileges, attach sudo su to the beginning of the command.

For example, you need sudo su to run a crontab command that edits other users’ scheduled jobs:

sudo su crontab -u username -e

In addition, you can add cron jobs to the etc/cron.d directory to store automatic installation and update scripts. To add them to this directory, you must have root access and conform to run-parts naming conventions.

Alternatively, a root user can move their cron job scripts into the following directories to schedule their execution:

  • /etc/cron.hourly/. Run the script once an hour.
  • /etc/cron.daily/. Run it once a day.
  • /etc/cron.weekly/. Run it once a week.
  • /etc/cron.monthly/. Run it once a month.

Using a Cron Job to Delete Scheduled Tasks

To delete all scheduled tasks in the crontab entries and start from the beginning, type the following command:

crontab -r

Alternatively, use the crontab -i command. It is similar to the previous one, except you will get a confirmation option before removing the crontab:

crontab -i

Conclusion

Cron daemon is a service in a Unix-based system that lets you create automation scripts for scheduling tasks. Meanwhile, cron jobs are the tasks automated using this tool, such as updating, installing, or monitoring a system.

To automate tasks, write the crontab command in your system’s cron file. The command contains the script for execution and five asterisks referring to the cron job’s execution time. Change the value of these asterisks and use the operators to modify the time.

To run a cron job, connect to your Linux operating system using Terminal, an SSH client, or another CLI application with root permission. Then, create a crontab file and add the script using a text editor like Nano.

Cron Job FAQ

In this section, we will answer several commonly asked questions about cron jobs to help you understand the tool better.

What Does a Cron Job Do?

Cron jobs are Linux commands for automating repetitive tasks on your server. It lets you schedule tasks for your system like updating, installing, or monitoring with a single command.

What Is the Use of * * * * * In Cron?

* * * * * is a cron schedule expression wildcard, meaning your cron job should run every minute, regardless of the hour, day, date, or month.

How Do I Run a Cron Job?

Log in to your server as the root user via SSH using PuTTY, Terminal, or Hostinger’s built-in Browser terminal. Then, create a file using the crontab -e command.

Choose an editor to view the file and add your cron job script to the blank crontab file. Save the file once you are done to enable the automation.

All of the tutorial content on this website is subject to Hostinger's rigorous editorial standards and values.

Author
The author

Linas L.

Linas started as a customer success agent and is now a full-stack web developer and Technical Team Lead at Hostinger. He is passionate about presenting people with top-notch technical solutions, but as much as he enjoys coding, he secretly dreams of becoming a rock star.

Author
The Co-author

Valentinas C.

Valentinas Čirba, Hostinger's Head of VPS, is a seasoned product leader specializing in VPS products with over ten years of experience. He's an expert at setting product strategy, leading cross-functional teams, and making smart decisions to deliver innovative solutions. Valentinas is committed to creating products that not only meet business objectives but also truly serve the customer. Follow him on LinkedIn.