Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using cron - Job Scheduling

Introduction to cron

Cron is a time-based job scheduler in Unix-like operating systems. Users can schedule jobs (commands or scripts) to run at specific times or intervals. It is very powerful and used for a wide range of tasks such as backups, system maintenance, and more.

Basic Syntax

The basic syntax of a cron job consists of five time-and-date fields followed by a command. The fields are:

  • Minute: 0-59
  • Hour: 0-23
  • Day of the month: 1-31
  • Month: 1-12
  • Day of the week: 0-6 (Sunday to Saturday)

The general format looks like this:

* * * * * command-to-be-executed

Setting Up a Cron Job

To set up a cron job, you can use the crontab command. This command allows you to install, deinstall, or list the tables used to drive the cron daemon.

To edit the crontab file, use:

crontab -e

This will open the crontab file in the default text editor. You can then add your cron jobs in the format described above.

Examples

Here are some example cron jobs:

0 5 * * * /path/to/backup_script.sh

This job runs a backup script every day at 5 AM.

30 2 * * 1 /path/to/cleanup_script.sh

This job runs a cleanup script every Monday at 2:30 AM.

Special Strings

Cron also supports special strings that can be used in place of the five time-and-date fields:

  • @reboot - Run once, at startup.
  • @yearly - Run once a year, equivalent to 0 0 1 1 *.
  • @monthly - Run once a month, equivalent to 0 0 1 * *.
  • @weekly - Run once a week, equivalent to 0 0 * * 0.
  • @daily - Run once a day, equivalent to 0 0 * * *.
  • @hourly - Run once an hour, equivalent to 0 * * * *.

For example, to run a script at every system reboot:

@reboot /path/to/startup_script.sh

Managing Cron Jobs

To list all the cron jobs for the current user, use:

crontab -l

To remove the current user's crontab, use:

crontab -r

To use a specific crontab file, use:

crontab /path/to/your/crontabfile

Environment Variables

Environment variables can be set in the crontab file. For example:

MAILTO="user@example.com"

This will send the output of the cron jobs to the specified email address. You can also set other environment variables as needed:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

Conclusion

Using cron is a powerful way to automate tasks on Unix-like systems. By understanding its syntax and options, you can schedule a wide range of jobs to suit your needs. Whether it's running backups, cleaning up logs, or sending out reminders, cron can handle it all with ease.