Today, while setting up scheduled tasks on Linux, I suddenly remembered that I could use Crontab for quick configuration.
Preparation#
Before we officially start, let's install some necessary programs, including the Crontab main body and editor selection.
Install Crontab#
First, we need to install Crontab. On Ubuntu and Debian, enter:
sudo apt install cron
For Fedora, Red Hat, or CentOS, enter:
sudo yum install cronie
Install Editor#
We also need a usable text editor; here we will use Nano for convenience.
To install on Debian and Ubuntu:
sudo apt install nano
To install on Fedora, Red Hat, and CentOS:
sudo yum install nano
Getting Started#
Below is how to use Crontab to add scheduled tasks, along with recommended tools for lazy people.
Manual Configuration#
Enter the following command in the command line:
EDITOR=nano crontab -e
This opens the Crontab configuration page, where you can add the commands you want to execute at scheduled intervals on the last line.
Below is the configuration format for Crontab, where the * * * * * corresponds to executing the command every minute.
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │ 7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * <command to execute>
Source: https://en.wikipedia.org/wiki/Cron
Automatic Generation#
Here are some websites that provide automatic generation of scheduled task configurations:
-
Chinese websites
-
English websites
After generating the corresponding configuration, refer to the manual configuration steps to insert it into the Crontab configuration file.
Q&A#
Q1. How to execute a command in a specific directory?
A1. Switch the path and then execute the command: cd /your/directory/ && [command]