TUX.. stay on schedule, you hear me?

Baby steps into automation: cron jobs

TUX.. stay on schedule, you hear me?

Table of contents

The following is a short piece on how to schedule jobs in a UNIX-like system. Only a month into CS engineering, and I'm already talking automation. It's surreal.

Enjoy!


CronJobs

Cron jobs (or Crons) refer to scheduled actions. crontab is a Unix utility that allows job-scheduling on an interval-basis, that is, a script is executed periodically. It's different from time-based crons that are performed only once on a specific date and time.

The cron syntax (illustrated below) is universal. It has 6 parts, of which the first 5 defines the interval, whereas the last one specifies the job.

The following are some example intervals:

# every min (base)
* * * * *
# 10th min every hour
10 * * * *
# every 10 mins 
*/10 * * * * 
# at 12am and 12pm on every Wed
0 0,12 * * 3
# every 2hrs on 15th and 30th
# of every month
0 */2 15,30 * *

Example

Set up a cron that backups all the files in ~/logs to ~/backup in zip format, every minute. Assume logs/ contains logs1.txt logs2.txt logs3.txt , which are updated by some editor.

p.s. the zip filename must be the current timestamp.

Solution

Step 1: Write the script.

# autoBackup.sh
zip -r ~/backup/$(date '+%Y-%m-%d-%H:%M').zip ~/logs/*.txt

Step 2: Check if the script works: bash autoBackup.sh. If yes, then change its permissions to make it executable: chmod 755 autoBackup.sh

Step 3: Add a new cron for every minute to the crontab file.

cmd: crontab -e

* * * * * ~/autoBackup.sh

Step 4: Save the file, and it's done. Now every min a new zip will appear in ~/backup


Thank You😊

See you soon✌️