How to add a Cronjob on Ubuntu 16.04

Alright my friends, it’s about time we talk about Cronjobs, specifically how to add a Cronjob on Ubuntu 16.04.

In yesterday’s tutorial, we were installing Certbot to auto renew our SSL certificates with a Cronjob, so I thought it might be a good idea to explain how Cronjobs work and how to set them up properly.

 

1. What is a Cronjob?

A Cronjob is a task that gets done automatically on a specific time. Let’s take sudo apt-get update for example.

If you want to keep your apt repository up to date at all times, you can utilize a Cronjob to do that for you, once a day for example.

 

2. How does a Cronjob work?

Let’s login to our Ubuntu instance for that. After you are in, run:

sudo crontab -e

 

If you run this for the first time, you will get asked which editor you want to use per default. I recommend using Nano for beginners.

And this is how your crontab file looks like when you first open it:

Now, when you look at the bottom like, you can see m h dom mon dow command

This is what you need to understand, so let’s break it down:

m h dom mon dow
Minute Hour Day of Month Month Day of Week

Alright, this should shed some light already.

Now we need to understand with which values we can work:

  • Minutes: 0 – 59
  • Hours: 0 – 23
  • DOM: 1 – 31
  • Month: 1 – 12
  • DOW: 0 is Sunday and 7 is Sunday for example:
    • 0 – 6 => Sunday – Saturday or
    • 1 – 7 => Monday – Sunday
    • You usually dont use 7 tho, only 0-6
  • * Is a Wildcard, which means basically if you take the minute field and put a wildcard in it, it will run every  Minute.

 

Let’s do a little test for yourself: Set a Cronjob that runs every Saturday at 14:30.

Answer:

Answer:

 

Alright, so this should give you a pretty good idea of how to set the time accordingly. The whole command would then look something like this:

15 23 15 * * sudo apt-get update

This would run sudo apt-get update at 23:15, every month on the 15th, no matter which day.

In case you really can’t wrap your head around it, head over to https://crontab.guru/ and let it do the thinking 🙂

 

3. Wrapping up

And finally let’s actually set the Cronjob on Ubuntu 16.04:

sudo crontab -e

Scroll down all the way to the bottom of the file and enter your desired time and command:

30 14 * * * sudo apt-get update

Hit CTRL + O to write the file and CTRL + X to leave (Nano)

 

And this concludes today’s lesson.

Once you understand how to set the time, it’s a piece of cake.

If this helped you a ton, you know what to do :))

Don’t forget to donate

🙂

Or, one of your favorite Cryptos:

Bitcoin Donations: 1KsqRQVg3caHFnYg8bvqR25sDDznpeNeCs
Ethereum Donations: 0xeB60dd10ab1146ad8504aEd127b6EF0168eF4FB5

All donations are highly appreciated!

 

Leave a Reply

%d bloggers like this: