Crontab Explainer

Crontab is a powerful utility tool included in the base package of almost all Linux distros. It enables you to automate your workflow by executing commands and scripts as scheduled tasks, aka cron jobs.

In essence, crontab is a command-line interface to the cron daemon (or crond), which runs in the background and executes tasks per the schedule specified in the crontab file.

When adding scripts to cron jobs, especially those that spawn processes or perform lengthy operations, it is crucial to exercise caution. If a script fails to exit properly or if multiple instances of the same script run simultaneously, it could quickly lead to unwanted behaviors. Your automation workflow can be interrupted, or your process limit can be reached, which results in your service becoming inaccessible.

To prevent such issues, ensure your script(s) includes proper exit conditions and, if needed, uses a locking mechanism. The file lock method is a simple yet effective solution. This approach ensures that only one instance of the script runs at any given time, preventing conflicts and potential interruption of your service. An example of where the lock file method has been used, can be found here.

The Crontab Format

Before setting up cron jobs, it is essential to understand the syntax of the crontab file. Each line in the crontab file represents a cron job consisting of a schedule and a command. A quick and straightforward way to configure cron schedules is to use crontab.guru.

* * * * * command_to_execute

For example, to run a command at 4:30 AM every day, the cron job would look like this:

30 4 * * * command_to_execute

Special Characters

Crontab also supports special characters that help in defining more complex schedules:

Configure Cron Jobs

To access the crontab, where you can create or edit cron jobs, connect to your service via SSH. Once connected, you can access the crontab by executing crontab -e.

ultra@docs:~$ crontab -e
no crontab for ultra - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        <---- easiest
  2. /usr/bin/vim.basic
  3. /usr/bin/mcedit
  4. /usr/bin/vim.tiny
  5. /bin/ed

Choose 1-5 [1]: 
1 12,00 * * * /home/username/scripts/myscript.sh >> /home/username/scripts/logs/myscript.log 2>&1
0 1 15,30 * * app-prowlarr upgrade >> /home/username/scripts/logs/prowlarr-upgrade.log 2>&1
0 2 15,30 * * app-jackett restart > /dev/null 2>&1

Revision #7
Created 21 August 2024 14:13:18 by varg
Updated 23 August 2024 07:23:00 by varg