Developer & Network Tools

Cron Jobs Explained

Read and write cron schedules, avoid the classic environment and timing traps, and make scheduled tasks report when they fail.

Key takeaways

  • A cron schedule has five fields in order: minute, hour, day of month, month and day of week.
  • Cron runs commands with a minimal environment, so use absolute paths and don't assume your usual shell settings.
  • Redirect both normal output and errors to a log, and arrange an alert for jobs that stop running.
  • Prevent a slow job from overlapping with its next run by using a lock.
  • Cron does not normally run jobs that were missed while the machine was off.

A cron job is a command that a Unix-like system runs automatically on a schedule. You write one line containing five time fields and a command, and the cron service runs that command whenever the clock matches: every night, every ten minutes, on the first of the month.

Websites lean on this for backups, sending queued email, clearing temporary files, renewing certificates and refreshing data. This article shows how to read the schedule syntax, add a job, and avoid the reasons jobs that work by hand fail on a timer.

How cron works

A background service, usually called cron or crond, wakes up every minute, compares the current time with each scheduled entry and starts the commands that match. Entries live in a file called a crontab ("cron table").

Each user can have a crontab, edited with a command and run with that user's permissions. There are also system-wide files, typically /etc/crontab and the /etc/cron.d/ directory, which include an extra field naming the user the job runs as. Many distributions also provide folders such as /etc/cron.daily/ where you drop a script without writing a schedule.

Three commands cover everyday management:

crontab -e   # edit your crontab
crontab -l   # list it
crontab -r   # remove it entirely, with care

Note how close -r sits to -e on the keyboard. Keeping a copy of your crontab in your project repository protects you from a slip.

Read the five fields

A crontab line looks like this:

30 2 * * 1 /usr/local/bin/weekly-report.sh

It means minute 30, hour 2, any day of the month, any month, on Monday. The script runs at 02:30 every Monday.

Reading the line 30 2 * * 1 command
30 1 2 2 * 3 * 4 1 5 command 6 Minute 0 to 59 1 Hour 0 to 23, on a 24-hour clock 2 Day of month 1 to 31; the star means any 3 Month 1 to 12 4 Day of week 0 to 7; both 0 and 7 usually mean Sunday 5 What to run Use the full path to the program or script 6 30 1 2 2 * 3 * 4 1 5 command 6 Minute 0 to 59 1 Hour 0 to 23, on a 24-hour clock 2 Day of month 1 to 31; the star means any 3 Month 1 to 12 4 Day of week 0 to 7; both 0 and 7 usually mean Sunday 5 What to run Use the full path to the program or script 6

Each field accepts a few operators:

Syntax Meaning Example in the minute field
* every value every minute
5 exactly that value at minute 5
1,31 a list at minutes 1 and 31
10-20 a range each minute from 10 to 20
*/15 steps minutes 0, 15, 30 and 45

Step values restart at each cycle. */40 in the minute field runs at minute 0 and minute 40 of each hour, which is not an even forty-minute rhythm.

One rule surprises almost everyone. If you restrict both day of month and day of week, standard cron runs the job when either one matches. 0 9 13 * 5 runs on every 13th and on every Friday, not only on Friday the 13th.

Schedules you can copy

*/5 * * * *    every five minutes
0 * * * *      at the start of every hour
15 3 * * *     every day at 03:15
0 8 * * 1-5    weekdays at 08:00
0 0 1 * *      midnight on the first of each month

Many implementations also accept shortcuts such as @daily, @hourly and @reboot. They are widespread but not guaranteed on every system.

A common typo is * 3 * * *, intended as "daily at 3". It actually runs every minute between 03:00 and 03:59. Always set the minute field deliberately.

When many jobs or many servers do the same thing, avoid scheduling them all on the hour. Picking an odd minute spreads the load, which matters when they all call the same outside service.

Add a job step by step

Say you want to clear old temporary files every night. A careful way to set that up has five steps.

  1. Write the task as a script rather than a long one-liner, so you can test it and keep it in version control. Begin it with a line such as #!/bin/sh so the system knows which interpreter to use.
  2. Make it executable with chmod +x /srv/app/cleanup.sh.
  3. Run it by hand as the same user the job will use, for example with sudo -u appuser /srv/app/cleanup.sh.
  4. Add the line with crontab -e, at first with a time a few minutes ahead so you can watch it fire.
  5. Once the log shows a successful run, change it to the real schedule.

Be especially careful with scripts that delete things. Check that the target directory variable is set and that the change of directory succeeded before removing anything, and try the command in listing mode first. A find command that prints matches can be reviewed safely before you add a delete action.

Comments help the next person. A line beginning with # above each entry saying what it does and who relies on it saves guesswork later.

Why it works by hand but fails in cron

Cron doesn't open your interactive shell. It runs commands with /bin/sh in most setups, a short PATH, no shell profile and often your home directory as the starting folder.

That explains the usual failures:

  • A program isn't found because it lives outside the short PATH. Run command -v php in your terminal and use the full path it prints.
  • A script can't find its files because it used relative paths. Start with cd /srv/app || exit 1.
  • An API key is missing because it was set in your profile. Load it explicitly from a protected file, as described in environment variables and secrets.
  • Permission is denied because the script isn't executable (chmod +x) or the job runs as a different user.
  • A percent sign breaks the line. In a crontab, % is special and has to be written as \%.

To reproduce the conditions, add a temporary job that writes env to a file, then compare the result with your own shell.

Capture output and errors

By default, cron tries to email a job's output to the owning user. On many web servers no mail system is configured, so the messages vanish. Send output to a log yourself:

15 3 * * * /srv/app/backup.sh >> /var/log/app/backup.log 2>&1

>> appends to the file and 2>&1 sends error messages to the same place. Make sure the job's user can write there, and set up log rotation so the file doesn't fill the disk.

Have scripts print a timestamp when they start and finish, and exit with a non-zero status when something goes wrong. The system log usually records that cron started a command, which tells you whether the schedule fired, but not whether the work succeeded.

Prevent overlapping runs

Cron starts a job on schedule even if the previous run is still going. An import that normally takes a minute can pile up copies of itself on a slow day, competing for the database and making each one slower.

On Linux, the flock utility solves this in the crontab line:

*/5 * * * * flock -n /tmp/import.lock /srv/app/import.sh

If the lock is already held, -n makes the new attempt give up at once. You can also add a time limit with the timeout command so a hung job cannot hold the lock forever.

Design the task so that running it twice does no harm. Marking records as processed, or writing to a temporary file and renaming it when complete, makes a repeat or an interruption safe. The same idea appears in retries and idempotency.

Notice when a job stops

The quietest failure is a job that no longer runs at all: the server was rebuilt without the crontab, the service stopped, or a line was commented out during testing. No error appears anywhere.

A heartbeat check catches this. The job notifies a monitoring service after each successful run, and the service alerts you when the expected signal doesn't arrive.

15 3 * * * /srv/app/backup.sh && curl -fsS https://monitor.example.com/ping/backup > /dev/null

The && means the ping is sent only when the script succeeds. For backups, also check now and then that the output can be restored, as covered in testing a website restore.

My cron job did not do its work
No sign in the system log that it started? YES Check the schedule, the crontab owner and that cron is running 1 NO Started but logged 'not found' or 'denied'? YES Use full paths and fix permissions 2 NO Runs by hand but not on schedule? YES Compare environments and working directory 3 NO Still running from last time? YES Add a lock and a time limit 4 NO Read the job's own log Add timestamps and exit codes, then run it again at a near time No sign in the system log that it started? 1 IF YES Check the schedule, the crontab owner and that cron is running NO Started but logged 'not found' or 'denied'? 2 IF YES Use full paths and fix permissions NO Runs by hand but not on schedule? 3 IF YES Compare environments and working directory NO Still running from last time? 4 IF YES Add a lock and a time limit NO Read the job's own log Add timestamps and exit codes, then run it again at a near time

Time zones, missed runs and alternatives

Cron normally follows the system's time zone. Where daylight saving time applies, a job scheduled in the early hours may be skipped or repeated on the changeover days, depending on the implementation. Running servers on UTC avoids this; see timestamps and time zones.

If a machine is asleep or off at the scheduled moment, standard cron doesn't catch up. Tools such as anacron, or systemd timers with the Persistent=true option, can run missed daily tasks after boot.

Other systems have equivalents. Windows uses Task Scheduler. macOS prefers launchd, though cron is present. Hosting control panels often provide a form that writes cron lines for you, and cloud platforms offer managed schedulers that use similar expressions, sometimes with extra fields. Check which dialect and time zone they use.

Some content management systems simulate scheduling by running due tasks when a visitor loads a page. On a quiet site that can delay work, so their documentation often suggests triggering it from real cron.

Common questions

Can cron run something every 30 seconds?

Standard cron's smallest unit is one minute. For shorter intervals, use a long-running worker process, a systemd timer with fine accuracy settings, or a queue.

Is it safe to run a job as root?

Only if the task needs it. Give routine web tasks their own limited user, and make sure no less privileged account can edit a script that root executes.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in Developer & Network Tools →

Latest news on this topic