Automate your tasks with Cron and Crontab
Tags: devops, unix, productivity
Published: 2023-08-23 00:25:46

<p align="justify">"In the digital age, efficiency and automation are essential to keep workflows agile and streamlined. Often, we find ourselves with tasks that need to be executed on a regular basis, whether it's backing up data, cleaning systems or generate reports.Instead of relying on manual intervention, which can be error-prone and time-consuming, wouldn't it be great to have a tool that allows us to schedule and automate these tasks?If you work with UNIX systems, you're in luck In this post, I'll introduce you to two powerful tools, Cron and Crontab, that can transform the way you manage and schedule tasks on your system. I'll share my recent experience with them and the essential lessons I've learned in the process."</p>

<p align="justify">I was recently given an assignment at work to learn how to use what is <a href="https://www.cbtnuggets.com/blog/technology/system-admin/how-to- use-cron-crontabs-to-schedule-linux-jobs" target="__blank">Cron and Crontab</a> so I immediately began to investigate what these tools are and what they are used for, and here are the conclusions I could reach.</p>

<h2>Cron</h2>

<p align="justify">It is a daemon-type service that comes installed with any UNIX system which is responsible for reading certain types of instructions from Crontab-type files.</p>

<h2>Crontab</h2>

<p align="justify">It is a text file in which each line indicates the frequency and the scheduled script that you want to be executed either once or several times.</p>

<p align="justify">Suppose we have prepared a certain bash script that we want to run constantly.</p>

<h2>1. Backup a folder recursively</h2>

<p>We have the following script that is responsible for compressing the information of a certain folder.</p>

<pre>
#!/bin/bash
# Folder you want to compress
SOURCE_DIR="/path/to/your/folder"
# Name of the compressed file to be generated
OUTPUT_FILE="/output/path/my_compressed_file.tar.gz"
# compress the folder
tar -czvf $OUTPUT_FILE $SOURCE_DIR
echo "The folder $SOURCE_DIR has been compressed into $OUTPUT_FILE"
</pre>

<p align="justify">We could manually execute said script every day at the times we deem necessary, but this could become somewhat repetitive and, above all, take away valuable time that we could be using in other types of tasks. Here comes what is Cron and Crontab.</p>

<ul>
<li>Open our terminal.</li>
     <li align="justify" >Run the command <code>vim crontab -e</code> This will open a screen similar to the following or it may show you a file with no text, which makes no difference. Now suppose we have saved the script to backup the information with the name <strong>makeBackup.sh</strong> and we want it to run every day at 8 am, 365 days a year.
         <div align="center">
                <img width="400" src="https://media.geeksforgeeks.org/wp-content/uploads/cron1-1.png">
         </div>
     </li>
     <li>Click the I key to put the VIM editor in edit mode and place the following line of code <code>00 08 * * * /path/makeBackup.sh</code></li>
</ul>

<p align="justify">Let's explain this little snippet</p>
<ul>
     <li><strong>00</strong> Will be executed at minute 00</li>
     <li><strong>08</strong> It will be executed at time 08</li>
     <li><strong>*</strong> It will be executed on any day of the month</li>
     <li><strong>*</strong> It will be executed in any month of the year</li>
     <li><strong>*</strong> Will run on any day of the week</li>
</ul>

<p align="jutify">Here you have in more detail the syntax structure of each line of a crontab file.</p>

<table border="1">
     <thead>
         <tr>
             <th>Position</th>
             <th>Description</th>
             <th>Values</th>
             <th>Example</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>1</td>
             <td>Minute of the hour</td>
             <td>0-59</td>
             <td>00</td>
         </tr>
         <tr>
             <td>2</td>
             <td>Time of day</td>
             <td>0-23</td>
             <td>08</td>
         </tr>
         <tr>
             <td>3</td>
             <td>Day of the month</td>
             <td>1-31</td>
             <td>*</td>
         </tr>
         <tr>
             <td>4</td>
             <td>Month</td>
             <td>1-12 (or names like JAN, FEB, etc.)</td>
             <td>*</td>
         </tr>
         <tr>
             <td>5</td>
             <td>Day of the week</td>
             <td>0-7 (0 and 7 are Sunday)</td>
             <td>*</td>
         </tr>
     </tbody>
</table>
<p>Note: The asterisk (*) in the crontab syntax is used to indicate "any value" or "always".</p>

<h2>2. Create a DB Backup Script</h2>

<h4>1. First, write a bash script that backs up your database.
   of data.</h4>

<pre>
#!/bin/bash

# Variables
DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="database_name"
BACKUP_DIR="/backup/path"
DATE=$(date +"%Y%m%d")

# backup
mysqldump -u$DB_USER -p$DB_PASS $DB_NAME > $BACKUP_DIR/db_backup_$DATE.sql

echo "Backup completed for $DATE"
</pre>

<p align="justify">Save this file as <code>db_backup.sh</code> and grant execute permissions with:</p>

<pre>
chmod +x db_backup.sh
</pre>

<h4>2. Configure Crontab</h4>

<p>To schedule the task, we are going to use Crontab.</p>

<ul>
     <li>Open your personal Crontab with the following command:</li>
</ul>

<pre>
crontab -e
</pre>

<ul>
     <li>To perform a daily backup at 2 a.m., add the following line:</li>
</ul>

<pre>
0 2 * * * /path/to/script/db_backup.sh
</pre>

<p>This line indicates:</p>
<ul>
     <li><code>0</code> Minute 0.</li>
     <li><code>2</code> Time 2 a.m.</li>
     <li><code>*</code> Any day of the month.</li>
     <li><code>*</code> Any month.</li>
     <li><code>*</code> Any day of the week.</li>
</ul>

<h4>3. Verify</h4>

<p align="justify">After adding the task to Crontab, make sure everything is working correctly. You can set the task to run in the next minute and verify that the backup file is created in the specified location.</p>

<p align="justify">This example shows how to automate daily backups of a MySQL database. The key is the combination of the script that performs the backup and Crontab that schedules the regular execution of the script. I hope this example is useful to you and inspires you to explore more about the automation possibilities with Cron and Crontab!</p>

<h2>Recommendations</h2>

<p align="justify">It is important to take into account the following aspects when working with task automation with Cront and Crontab.</p>

<ul>
<li align="justify">Always place an email at the beginning of the crontab file with the snippet <code>MAILTO="yourmail@hotmail.com"</code>, this is quite useful for when the Cron daemon have to execute the script if there is an error in the script's syntax, you will receive the error in your email.</li>
     <li align="justify">Use absolute paths to your scripts</li>
     <li align="justify">Test your scripts by scheduling tasks to run within 5 minutes, so you can instantly debug any possible errors either in the way the task is scheduled, the script path, or in the script itself .</li>
     <li align="justify">When creating your .sh scripts give it execute permissions, you can use <code> chmod +x file.sh</code></li>
</ul>

<p align="justify">Did you find this tutorial on Cron and Crontab helpful? Task automation is just the tip of the iceberg when it comes to maximizing efficiency on UNIX systems. If you want to learn more and keep your skills up to date, subscribe to my <a href="https://phillipcabrera.com/" target="__blank">blog!</a>. And if you think this article can help someone else, don't hesitate to share it on your social networks! Remember, sharing knowledge is a way to empower our tech community.</p>