Wisdom Ekpot A student of Ibom Metropolitan Polytechnic studying computer engineering, Wisdom has been writing JavaScript for two years, focusing on Vue.js, Angular, and Express.js.

Setting up cron jobs in Deno

3 min read 993

Deno Logo

Automation can save time by improving and streamlining processes and repetitive tasks. In a unix-like system, you can automate tasks using cron jobs.

What is a cron job?

A cron job is a unix term for a system process (cron) that allows you to schedule tasks to run at a later date under a specified set of privileges. Essentially, it’s a scheduler that enables applications to schedule a job to run automatically at a certain date or time. In this article, we’ll integrate a cron job into a Deno application.

Prerequisites

  • An understanding of JavaScript
  • A text editor (in our case, we will use VS Code)
  • POSTMAN installed on your local machine

Installing Deno

If you don’t have Deno already installed on your local machine, you can install it using Homebrew:

brew install deno

When the installation is complete, run deno on your terminal to confirm that the installation was successful.

Deno has a smart job scheduler library that we will be using. We will start by creating a directory for our application in our home directory:

cd desktop && mkdir denocron && cd denocron
touch index.ts

To implement cron jobs in our application, we have to import the module into our application:

import {cron, daily, monthly, weekly} from 'https://deno.land/x/deno_cron/cron.ts';

Apart from defining a custom time for a task to run, Deno cron already provides some methods to create weekly, monthly, and daily schedules.

Defining a custom schedule in Deno

We can use this module to create a custom time for a task to run by using the cron method. This method schedules tasks using the cron pattern, which has a format like this:

cron('* * * * * *', () => {
    // run some task
});

Let me explain what is happening here.

  • The first asterisk takes the number of seconds. This takes a value between 0-59
  • The second asterisk takes the number of minutes and also takes a value between 0-59
  • The third asterisk takes the number of hours, which has a value between 0-23
  • The forth asterisk takes the day of the month, which has a value between 0-31
  • The fifth asterisk takes the month of the year, which has a value between 0-31
  • The sixth asterisk takes in the day of the week and has a value between 0-7

We can write a simple job that will run every second:

cron('*/1 * * * * *', () => {
    // run some task
    console.log('This is a same thing')
});

To run our application, open up the terminal and run deno run index.ts.

Using Denon to run our application

Just like Node.js has nodemon, Deno also has denon package that reloads our application whenever a change is made.

To install this, open up your terminal and run this command:

deno install -qAf --unstable https://deno.land/x/[email protected]/denon.ts

This command will install the denon package globally on our development machine.

Now that we can run our application, we can use this command: denon index.ts. If you are using a MacBook, you might run into an error saying command not found: denon, like so:

An Error Showing the Command Wasn't Found

If you encounter this error, you can do one of the following:

If you are using a zsh terminal, you can configure this by running:

export PATH="/Users/<user>/.deno/bin:$PATH"

Where the <user> directory is the name of your account on your local machine.

And if you are using a bash terminal, you can use this command to configure it:

echo 'export PATH="$HOME/.deno/bin:$PATH"' >> ~/.bashrc

Use case of cron jobs: automated emails

A common use case for cron jobs is creating automated sending of emails and newsletters. We can write a simple function that is capable of executing a function every first day of the month at midnight. We will use the cron method for this:

cron('1 0 0 1 */1 *', () => {
    // run a function
});

This method takes the schedule configuration and the method to be called when the schedule is due to run.

We can write a simple cron job that will run every 30 seconds:

let task = cron('*/30 * * * * *', () => {
    // run some task
    console.log('This is a same thing')
});

And here’s a simple job that will run every 30 minutes:

cron('1 */30 * * * *', () => {
    checkStock();
});

Apart from defining custom jobs, Deno cron comes with its own built-in method. For example, we have the daily, weekly, and monthly methods, which will run at the specified time:

daily(() => {
    console.log('I run on daily basis')
});

weekly(() => {
console.log('This method will run on weekly bases')
});

everyMinute(()=> {
  console.log('This method will run on 60 seconds')  
})

To use this method, we have to import it first:

import { cron, everyMinute, daily, weekly } from 'https://deno.land/x/deno_cron/cron.ts';

To stop all cron jobs, we can use the stop() method. To start all cron jobs, use the start() method.

To see how this works, let’s set some boolean values. First, import this method:

import { cron, start,stop } from 'https://deno.land/x/deno_cron/cron.ts';
let task = cron('*/1 * * * * *', () => {
    // run some task
    console.log('This is the same thing')
});
let someBool = false
if (someBool) {
    start()
} else {
    stop()
}

We start by importing the cron , start, and stop method from the url and then use the cron method to create a job that will run every minute.



To run the application, set the value of someBool to true. Once this is done, the job will log This is the same thing on the console every one minute. Also notice that the start and stop methods are used to control the flow of the job.

"This is a same thing" Logging Automatically

Conclusion

Cron jobs can come in handy when building a large scale application where you want to send scheduled newsletters to all your customers, automate any of your messages, or complete automated tasks.

Here’s the source code of this project.

Get setup with LogRocket's modern error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now
Wisdom Ekpot A student of Ibom Metropolitan Polytechnic studying computer engineering, Wisdom has been writing JavaScript for two years, focusing on Vue.js, Angular, and Express.js.

Leave a Reply