:bulb: This guide covers how to use Cron (crontab) to run desired tasks automatically at specific times.

[01] What is Cron?

A time-based job scheduler on Linux. Use it when you need to run a task periodically at a specific time, date, or interval. Configure and run jobs using crontab.

[02] Install

1
2
sudo apt-get install update
sudo apt-get install cron

[03] Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# View the current user's crontab
crontab -l

# Edit the current user's crontab
crontab -e

# Remove the current user's crontab
crontab -r

# ex)
root@emaster:~# crontab -l
no crontab for root
root@master:~# crontab -e
no crontab for root - using an empty one
crontab: installing new crontab

root@master:~# crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

51 14 19 * * /root/code/.venv/bin/python3 /root/code/test.py

2023-07-19 14 50 20

[04] Configuration (Rules)

1
2
*  *  *  *  *   command
m  h  dom mon dow
  • minute (0-59), hour (0-23), day of month (1-31), month (1-12), day of week (0-6: 0 = Sunday, 6 = Saturday)
1
2
3
4
# On the 19th of every month, at 14:51,
# run the /root/code/test.py program
# inside the /root/code/.venv/bin/python3 Python virtual environment
51 14 19 * * /root/code/.venv/bin/python3 /root/code/test.py

:small_blue_diamond:Reference: Verify schedule timing (crontab.guru)

[05] Service Control

1
2
3
4
5
6
7
8
# Check status
service cron status

# Start
service cron start

# Stop
service cron stop

[06] Extra: Running from a Python Virtual Environment

When you want a Python script to run inside a virtual environment, include the shell shebang line at the top of the Python file.

1
2
#! /root/code/.venv/bin/python3 /root/code/test.py
print("Hello")