Ubuntu 22.04 Cron

From CompleteNoobs
Jump to navigation Jump to search
Please Select a Licence from the LICENCE_HEADERS page
And place at top of your page
If no Licence is Selected/Appended, Default will be CC0

Default Licence IF there is no Licence placed below this notice! When you edit this page, you agree to release your contribution under the CC0 Licence

Cron Quick Start

Cron already comes preinstalled - but if not, install with
sudo apt install cron

Cron is a time-based job scheduler in Ubuntu and other Unix-like operating systems. It allows users to schedule commands or scripts to run automatically at specific times or intervals. Cron jobs are very useful for automating repetitive tasks or performing maintenance tasks on a regular basis.

To use cron on Ubuntu, you need to understand the syntax of the cron schedule and how to set up a cron job.

The cron schedule consists of five fields: minute, hour, day of the month, month, and day of the week. Each field can be specified with a single value, a range of values, or a list of values separated by commas. Asterisks (*) can be used as wildcards to specify all possible values.

To set up a cron job, you can use the crontab command to edit the cron table. This table contains a list of cron jobs for the current user. Each cron job is specified on a separate line, and consists of the schedule and the command to be executed.

For example, to schedule a script to run every day at midnight, you would add the following line to the crontab:
0 0 * * * /path/to/script.sh
This cron job runs the script.sh file located at /path/to/ every day at midnight (00:00).

* is an asterisk is a wildcard variable that represents all, every day, every hour ... etc

Syntax: From left to right.
The first 5 are for time. When to run.
Minute: 0-59
Hour: 0-23
Day (of the month): 1-31
Month: 1-12 or JAN-DEC
Day (of the week): 0-6 or SUN-SAT
/ can be used to create a step value.

Followed by the Command or Script:
0 5 * * SUN /usr/local/bin/script.sh will run the script at 5am on sunday.

*/1 * * * SUN,MON /usr/local/bin/test.sh will run every minute on sundays and mondays.

30 3 */3 * * /usr/local/bin/test.sh will run script at 3:30am every 3 days.
crontab -e to edit your cron file.

Example to play with: