Schedule tasks on Linux using Cron

Overview

Cron is the time-based job scheduler in Unix-like computer operating systems.
Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates.
It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes.

using Cron

General Information

To edit the Cron Table use:
[code lang=”bash” inline=”yes”]crontab -e[/code]

To view the Cron Table use:
[code lang=”bash” inline=”yes”]crontab -l[/code]

The crontab file

Minute Hour Day of Month Month Day of Week Command
(0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat)

Using Cron Examples

Run ‘check.sh’ script every 3 Minutes :
[code lang=”bash” inline=”yes”]*/3 * * * * /scripts/check.sh[/code]

Run ‘check.sh’ script every Day at 07:00 :
[code lang=”bash” inline=”yes”]0 7 * * * /scripts/check.sh[/code]

Run ‘check.sh’ script every 24th of the Month at 13:10 :
[code lang=”bash” inline=”yes”]10 13 24 * * /scripts/check.sh[/code]

Run ‘check.sh’ script every Sunday at 21:53 :
[code lang=”bash” inline=”yes”]53 21 * * 0 /scripts/check.sh[/code]

Additional Info

Adding Environment Variables :
Cron doesn’t export any of the profile files,
so if you need a path variable you can set it in crontab (using crontab -e) :
[code lang=”bash” inline=”yes”]
PATH=$PATH:/sbin:/bin/usr/local/bin:/usr/local/sbin:/scripts
0 * * * * root /scripts/check.sh[/code]

Output your command to a log file :
[code lang=”bash” inline=”yes”]0 * * * * /sbin/ping -c 10.0.0.1 >> /scripts/cron.log[/code]

Run as a different user (for example root) :
[code lang=”bash” inline=”yes”]0 * * * * root /scripts/check.sh[/code]

Leave a Reply

Your email address will not be published.

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.