Crontab - Technological watch

Learn what is a Crontab in less than 5 minutes !
Tuesday, May 17, 2022

Introduction

Crontab is a tool used to run commands or scripts on a schedule.

The use cases would be:

  • Make backups every day
  • Renew your SSL certificates
  • Schedule long-running tasks like sending mass e-mails
  • Clear the temporary files
  • Check for updates
  • Put some data in a cache
  • Optimize SQL databases
  • And a lot of other cases ! šŸ˜Š

Installation

Usually, it is installed by default. But you can find the package:

Terminal window
# Debian:
apt-get install cron

Usage

To list all the jobs you have in your crontab profile, you can do:

Terminal window
crontab -l

To edit the jobs, you can do:

Terminal window
crontab -e

Syntax

The crontab syntax is simple and looks like this:

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * [user command to be executed]

You can use caracter values like:

`*` Any value
`,` Value separator (ex: `2,4` represents 2 AND 4)
`-` Range of values (ex: `1-5` represents 1,2,3,4,5)
`*/12` Every 12th unit of time

Examples

Here as some examples to better understand:

If you want to run a script every day at 1am (and 0 minutes), you can write:

0 1 * * * bash /home/alex/my_script.bash

If you want to run a script every 5 minutes:

*/5 * * * * bash /script.bash

Or you can do more specific tasks: At 22:00 on every day-of-week from Monday through Friday.

0 22 * * 1-5 bash /script.bash

Configuration

You can deny or allow a user to modify his crontab.

To do this, create a file /etc/cron.allow or /etc/cron.deny.

  • If /etc/cron.allow file exists, you need to be in this file to write crontab.
  • If /etc/cron.deny file exists, you need to NOT be you can deny or allow a user to modify his crontab.

The best case is to create only one of these two files, and set the users you want into. in the file to be able to use write a crontab.

The best case is to create only one of these two files, and set the users you want into.

The root user bypass these verifications.

āš ļø The /etc/cron.allow and /etc/cron.deny files manage the access to the crontab command. If a user has a crontab, and after we remove it from the /etc/cron.allow file, the tasks will still be run !

More

If you want to test your crontabs, there is a nice website that you can find here: https://crontab.guru.

You can find cron alternatives in your favourite language like Nodejs (https://www.npmjs.com/package/cron), or in python (https://github.com/dbader/schedule)


Recommended articles