DEV Community

anubhav_sharma
anubhav_sharma

Posted on

Write your first Cron Job with me.

Cron Image
For a long time, I was having an urge to write a cron job to automate some tasks. Here is a summary so you can do it too.

  1. Little Background
  2. Setup
  3. Write your cron job

1. Little Background

1. What is Cron?

In simple words, it is a scheduler

2. What does a scheduler do?

runs a specified task at a specified time

3. Where can you use it?

to automate any repeated task like syncing data or taking backups etc.

4. How to write Syntax for cron.

for writing a cron file you just need
(specify the time)+ (specify the task)

Cron syntax sample

In General to specify the time we have 5 parameters (* * * * *)

  1. minute
  2. hour
  3. day (month)
  4. month
  5. day (Week)

Example
45 23 * * 6 /home/oracle/scripts/export_dump.sh

In addition to this we could use some arbitrary scheduler expression such as

  1. @yearly
  2. @monthly
  3. @weekly
  4. @daily

Example
@weekly /bin/script.sh
This will run the script once in a week.

Cron expression syntax is very important for it to work use websites like https://crontab.guru/ and ensure that it works properly.

Explanation for cron expression syntax


2. Setup

Although cron is installed in most Linux distributions you can check if it is present or not.
Just Type crontab and check.


3. Write your cron Job

1. To see if any cron job already exists

crontab -l

2. Let's write a new cron job

crontab -e
and since cron uses vi by default you may use the below command to edit it using your favorite editor
EDITOR=/usr/bin/vim crontab -e

3. Running a sample cron job

Open up your crontab and write
0 0 * * * date >> /tmp/cron_output

This will run every day at 00:00 in 24-hour format or 12:00 am in 12-hour format and will output the current date to /tmp/cron_output.


Tips

  1. Tests your cron job before deploying.
  2. Remember that cron jobs run on a separate thread(daemon thread) and sometimes may have different behavior than intended.

Stay tuned for more.
Next coming up: Sending Automated WhatsApp message using cron

Top comments (0)