What is a Cronjob?

A cronjob is a time-based scheduler in Unix-like operating systems that automates repetitive tasks by running commands or scripts at specified intervals. It's the backbone of server automation, quietly handling everything from database backups to log cleanup without human intervention.

This guide covers how cron scheduling works, breaks down the syntax with practical examples, and walks through best practices for reliable job management.

What is a Cronjob

A cronjob is a time-based scheduler in Unix-like operating systems such as Linux and macOS that automates repetitive tasks like backups, report generation, or script execution. Using a specific syntax called a cron expression, it defines when commands or scripts run, ensuring tasks execute consistently in the background without anyone clicking a button or typing a command.

The name "cron" comes from the Greek word "chronos," meaning time. Three related terms often come up together, and understanding the difference between them helps clarify how the whole system works:

  • Cron: The background daemon (a system process that runs continuously) checking for and executing scheduled tasks.
  • Cronjob: A specific task scheduled to run automatically at defined intervals.
  • Crontab: The configuration file where users define their cron jobs.

How Cron Job Scheduling Works

Cron job scheduling relies on a five-field time format that determines exactly when a job executes. The cron daemon reads these fields from left to right, and each field represents a different unit of time.

The Cron Schedule Format

The structure follows this pattern: minute hour day-of-month month day-of-week command. Here's what each field accepts:

FieldValue RangeDescription
Minute0-59Minute of the hour
Hour0-23Hour of the day (0 = midnight)
Day of Month1-31Day of the month
Month1-12Month of the year
Day of Week0-6Day of the week (0 = Sunday)

Minute

The minute field accepts values from 0 to 59. Setting this to 30 means the job runs at 30 minutes past the hour, every hour that matches the other fields.

Hour

The hour field uses a 24-hour format, where 0 represents midnight and 23 represents 11 PM. A value of 14 means the job runs at 2 PM.

Day of Month

This field specifies the calendar date, ranging from 1 to 31. One thing to keep in mind: if you set a value like 31, the job won't run in months with fewer days, such as February or April.

Month

The month field accepts numeric values from 1 to 12. Some cron implementations also accept three-letter abbreviations like JAN, FEB, or MAR, which can make expressions easier to read at a glance.

Day of Week

This field ranges from 0 to 6, where 0 typically represents Sunday. On some systems, Sunday can also be represented as 7, so checking your specific cron implementation helps avoid confusion.

Cron Expression Syntax Explained

A cron expression combines all five time fields with special characters that add flexibility. These characters allow you to create schedules ranging from "every minute" to "the third Tuesday of each quarter at 3:15 AM."

Standard Characters

Four special characters appear in most cron expressions:

  • Asterisk (*): Matches all values in a field. An asterisk in the hour field means "every hour."
  • Comma (,): Lists multiple specific values. Using 1,15,30 in the minute field runs a job at minutes 1, 15, and 30.
  • Hyphen (-): Specifies a range. Using 9-17 in the hour field means every hour from 9 AM to 5 PM.
  • Slash (/): Defines step values. Using */10 in the minute field means "every 10 minutes."

Special Operators and Wildcards

Some cron implementations support additional characters for complex scheduling. These include the question mark (?), L (last day), W (weekday), and hash (#) symbols. Availability varies between systems, so checking documentation for your specific cron version helps avoid unexpected behavior.

Predefined Scheduling Shortcuts

Many modern cron systems support shortcuts that simplify common scheduling patterns:

  • @hourly: Runs once per hour, equivalent to 0 * * * *
  • @daily: Runs once per day at midnight, equivalent to 0 0 * * *
  • @weekly: Runs once per week on Sunday at midnight
  • @monthly: Runs on the first day of each month at midnight
  • @reboot: Runs once when the system starts up

Crontab vs Cronjob

People often use these terms interchangeably, but they refer to different things. The crontab is the file and command used to manage jobs, while a cronjob is the individual scheduled task itself.

  • Crontab file: A text file storing all scheduled cron jobs for a specific user.
  • Crontab command: The command-line utility for managing schedules. Use crontab -l to list jobs, crontab -e to edit, and crontab -r to remove all jobs.
  • Cronjob: A single line entry within a crontab file defining one scheduled task.

Think of the crontab as a to-do list and each cronjob as an individual item on that list.

Cron Job Examples

Seeing practical examples makes cron expressions click. Here are common scheduling scenarios that cover most everyday use cases.

Run a Job Every Minute

* * * * * /path/to/script.sh

Each asterisk means "every," so this expression executes the script every minute of every hour of every day. This pattern works well for monitoring scripts or tasks requiring near-real-time execution.

Run a Job at Midnight Daily

0 0 * * * /path/to/script.sh

This runs the script at minute 0 of hour 0 (midnight) every day. Nightly maintenance tasks, database cleanups, and daily report generation often use this pattern.

Run a Job Every Weekday at 9 AM

0 9 * * 1-5 /path/to/script.sh

The 1-5 in the day-of-week field limits execution to Monday through Friday. Business-hour automation, like sending daily team updates or generating morning reports, fits this pattern well.

Run a Job on the First of Each Month

0 0 1 * * /path/to/script.sh

The 1 in the day-of-month field ensures this runs only on the first day of each month at midnight. Monthly billing processes, subscription renewals, and end-of-month reports typically use this schedule.

Run a Job Every 15 Minutes

*/15 * * * * /path/to/script.sh

The step value syntax (/) divides the hour into 15-minute intervals, running at minutes 0, 15, 30, and 45. Health checks, cache refreshes, and data synchronization tasks often run on this kind of interval.

Common Cron Job Use Cases

Organizations rely on cronjobs because they provide a simple, reliable way to handle repetitive tasks without human intervention. Here are the most common applications.

Automated Database Backups

Scheduling regular database exports using tools like mysqldump helps prevent data loss. Many teams run backups during off-peak hours to minimize performance impact on production systems.

Scheduled Report Generation

Automating the creation and distribution of business or system performance reports saves time and ensures consistency. Reports can be generated and emailed to stakeholders on a set schedule without anyone remembering to run them manually.

Log Rotation and Cleanup

Servers generate large amounts of log data over time. Cronjobs can archive or delete old log files to free up storage space and maintain system performance before disk space becomes a problem.

Email and Notification Scheduling

Automated reminders, newsletters, or daily digest emails often run on cron schedules. This ensures timely delivery without manual effort and keeps communication consistent.

Cache Management

Clearing or refreshing cached data on a set schedule keeps application content current. Websites with frequently changing content particularly benefit from scheduled cache invalidation.

Cron Job Limitations

While cronjobs are powerful, they have constraints worth understanding before implementation.

Time Zone Handling Issues

Cron uses the server's system time by default. This can cause confusion when managing servers across different time zones or when daylight saving time changes shift schedules unexpectedly.

No Native Error Handling

Cron jobs can fail silently without proper configuration. There are no built-in alerting or automatic retry mechanisms, so a failed job simply doesn't run, and no one knows unless they check.

Concurrency Conflicts

If a job takes longer than its scheduled interval, multiple instances can start running simultaneously. This overlap can cause data corruption, duplicate processing, or excessive server load.

Environment Variable Differences

Cron runs with a minimal shell environment that differs from an interactive terminal session. Scripts depending on environment variables from a user's profile may behave differently or fail entirely when run by cron.

Best Practices for Cron Job Management

Following these guidelines helps create reliable, maintainable cron job schedules that don't cause headaches down the road.

1. Always Log Output

Redirect both standard output and errors to a log file for debugging. For example: * * * * * /path/to/script.sh >> /var/log/myjob.log 2>&1. Without logging, troubleshooting failed jobs becomes guesswork.

2. Use Absolute File Paths

Avoid relative paths since cron's working directory may not match your expectations. Always specify full paths like /usr/bin/php instead of just php, and use complete paths for any files your script reads or writes.

3. Implement Monitoring and Alerts

Use external monitoring tools to track job execution and receive alerts when jobs fail or don't run on schedule. Services sometimes called "dead man's switches" can notify you when an expected job doesn't check in.

4. Document Every Scheduled Job

Add comments in your crontab file explaining what each job does, why it exists, and who to contact about it. Future you, or whoever inherits the system, will appreciate the context.

5. Test in a Staging Environment First

Validate new cron expressions and scripts in a non-production environment before deploying to live servers. A typo in a cron expression can mean a job runs every minute instead of every month.

Choosing the Right Cron Scheduler for Your Needs

Traditional cron works well for server-based automation, while web-based services like cron-job.org offer alternatives for simpler scheduling needs without server access. The right choice depends on what you're automating and where your systems live.

For organizations managing people-focused processes like performance reviews, goal tracking, and employee development, purpose-built platforms often work better than cobbling together cron-based solutions. Engagedly automates HR workflows without requiring technical configuration, handling the scheduling complexity behind the scenes.

Book a demo to see how Engagedly can automate your talent management processes.

FAQs about Cron Jobs

What does cron 30 4 1,15 * 5 mean?

This expression runs a command at 4:30 AM on the 1st and 15th of every month, but only when that day falls on a Friday. The comma separates multiple day-of-month values, while the 5 in the day-of-week field specifies Friday.

Can cron jobs run every second?

No, the minimum interval for a standard cron job is one minute. The smallest time unit in the cron schedule format is the minute field, so sub-minute scheduling requires alternative tools or workarounds like running a script that loops internally.

How do I check if a cron job is running?

Use crontab -l to list all scheduled jobs for the current user. To verify active execution, check system logs (typically /var/log/cron or /var/log/syslog) or use process-monitoring commands like ps aux | grep [script_name].

What happens when a cron job fails?

By default, cron attempts to email the job owner with any output or error messages. The job won't automatically retry unless you've configured retry logic in a wrapper script, and without email configured, failures can go completely unnoticed.

How do I remove a cron job from crontab?

Edit the crontab file using crontab -e, delete the line containing the job you want to remove, then save and exit. Alternatively, crontab -r removes the entire crontab file, though this deletes all scheduled jobs for that user, so use it carefully.

×

Contact Us