Always do things on time with a Cron job.
Tags: linux, devops, codenewbie, webdev
Published: 2021-09-04 07:58:04

No. This will not help you fix that exercise schedule. Nor will it help you go to sleep on time without looking at your phone for hours. But you servers can sure get a lot of things done without needing human intervention.

## Cron
A time-based task scheduler created for Unix-like systems with the purpose of executing system administration and maintenance tasks.

With advancement of technologies, it was found useful in other aspects of software development. This led to libraries and frameworks being built to implement Cron in different environments like web application development.

Let's talk about Cron as an abstract concept.

### 1. Cron Expression
To run something periodically, you need a way to define the period. In human terms, we would say daily, yearly, hourly, every Friday, every 3rd day, etc. And yes, you can do all this with Cron jobs as well. Let's look at one puzzling example 

Full expression
```bash
0 0/50 13-14 ? JAN,MAR,JUL 2/3 2026/2
```

|Seconds|Minutes|Hours|Days of Month|Months|Days of week|Year|
|-------|-------|-----|-------------|------|------------|----|
|0|0/50|13-14|?|JAN,MAR,JUL|2/3|2026/2|
|At second :00|every 50 minutes starting at minute :00| every hour between 13pm and 14pm||in January, March and July |every 3rd day of the week starting on Monday|every 2 years starting in 2026|

The full description 
> "At second :00, every 50 minutes starting at minute :00, every hour between 13pm and 14pm, every 3rd day of the week starting on Monday, in January, March and July, every 2 years starting in 2026"

Yeah, I'm a bit crazy to puzzle you with this but easier things are easier to forget. So go figure it out. 
For a further explanation refer to [Wikipedia](https://en.wikipedia.org/wiki/Cron#CRON_expression)

Some things to remember while making cron expressions:
1. Sequence - **Seconds Minutes Hours "Days of Month" Months "Days of week" Year**
2. Range is Indicated by "-"
3. Start/Repetition are written like 5/10 - starts at 5 and repeats after every 10 units of time.
4. Specific values - comma-separated values like "JAN, MAR, JUL"
5. Leave anything blank with "?" - only works with Days of week and Days of month
6. Repeat on every 1 unit of time - use an asterisk "*"

### 2. Crontab entry

A crontab file is a file containing job entries. You don't normally work with crontab files directly and rather use CLIs or programs to do so.

![Crontab entry](https://tecadmin.net/wp-content/uploads/2013/03/crontab-2.png)

An entry contains the below format
**Expression Command**

For e.g.
```
1 0 * * * printf "" > /var/log/apache/error_log
```
clears the Apache error log at one minute past midnight (00:01) every day

You can use any command here that can be run on a terminal.
For e.g.
1. Cleanup unused docker images.
2. Start/stop programs.
3. Query an API with curl.

### 3. Cron Daemon 
If you're familiar with the concept of daemons, this will be easy to understand. A Daemon is a system program which once started keeps running in the background until stopped. Its purpose is to provide a platform - *a set of common services* - for tasks to run on top of it. 

![Cron daemon managing things](https://miro.medium.com/max/780/0*pYdmponVyI4hIzol)


Now that you have defined your expression and tasks, the daemon connects the dots for you.

In this case, the daemon's responsibilities are:
1. Read a list of cron jobs from a source (crontab file in linux)
2. Use the cron expressions of the job to calculate the timestamp when these tasks will run next and maintain it in memory (called an event time list)
3. Loop through the tasks in the event list
    - Sleep until there is a task to run. 
    - Wake up and run the next task.
    - Once task is started, calculate the next timestamp of the same task and put it in the event list.
    - Repeat for the next task.

Now that you know how cron works, lets look at some of its **use cases**:
1. CI/CD - deploying at a fixed time.
2. Cache expiry/re-bake - Clear or re-create cache after an interval.
3. Reminders and Newsletters - Send emails at a point in time or at regular intervals.
4. SysAdmin tasks - Daily backups, security scans, auto-shutdown servers, etc.

Hope you found this small introduction to cron useful and it adds value to your day to day solutioning. 

Here are some useful resources to get you to the next level:
1. Create and validate cron expressions with [FreeFormatter](https://www.freeformatter.com/cron-expression-generator-quartz.html)
2. Learn and experiment with [cron on Linux](https://www.computerhope.com/unix/ucrontab.htm) 
3. Checkout how to use [node-cron](https://github.com/node-cron/node-cron) to run cron job with JavaScript.


---

Stay tuned for more.

You can connect with me on [Twitter](https://twitter.com/abh1navv)