DEV Community

Cover image for Scheduling tasks in NodeJS with cron job
Kayode
Kayode

Posted on • Updated on • Originally published at blog.zt4ff.dev

Scheduling tasks in NodeJS with cron job

The cron command-line utility, also known as cron job, is a job scheduler on a Unix-like operating system. Users who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the internet and downloading email at regular intervals.

A cron job is defined by using a series of asterisks (*****) which denotes different timing as indicated below.

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
# │ │ │ │ │                                   
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
Enter fullscreen mode Exit fullscreen mode

This is very useful when you perform repetitive tasks that can be done programmatically for instance clearing logs, downloading files from the internet regularly or sending SMS to your spouse regularly from a Love SMS API ****😓

red_skull.jpeg

Examples of cron-job in a GNU system

The following command runs the ./clean_file.sh script file regularly at 1 minutes past midnight everyday

1 0 * * * ./clean_file.sh
Enter fullscreen mode Exit fullscreen mode

More Examples of cron job notation

  • 45 23 * * 6 - runs on Saturdays at 23:45 (11:45pm)
  • 0 0 25 12 * - runs at midnight on 25th of December (Christmas day)
  • 0 0 * * * - runs at midnight everyday
  • * * * * * - runs every minute
  • * 10,14 * * *- runs everyday at 10:00 (10am) and 14:00 (2pm)
  • 0 0 14 2 * - runs every 14th day in February and at midnight

To use the cron notation to schedule tasks in our application, we will install the node package node-cron running the command below in our terminal.

npm install node-cron 
Enter fullscreen mode Exit fullscreen mode

Bree is another package with support for workers threads and cron syntax. But for the purpose of this article, we will stick to node-cron. So let's run a simple example:

const cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});
Enter fullscreen mode Exit fullscreen mode

So you could perform basically any function at different scheduled dates by passing the function as a second argument.

Running in background

on Linux you can run the program in the background by using the ampersand & sign behind the command:

node app .js &
Enter fullscreen mode Exit fullscreen mode

And use the command jobs to see the running processes in the background.

A similar command on Powershell is known as Start-Job

Thanks for reading through, I hope you liked this article 🤗

If you enjoy reading this article, you can consider buying me a coffee

Connect with me on Twitter and LinkedIn

Oldest comments (6)

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

Thank you very much!
What would be the simplest cron job notation to run every last day of every month including a leap-year?

Collapse
 
zt4ff_1 profile image
Kayode • Edited

There's no single cron notation to run a task every last day of the month. You can run the task at the first day of the month at midnight or make use of npm module like bree to run the task at the last day of the month or have mutiple cron jobs for a single task.

But if you want to stick to cron, a simple solution is to run the tasks from 28 - 31 every month but make use of any robust date framework (that what date tomorrow is) to determine if any of the date is the last date. For instance

cron.schedule("0 0 28-31 * *", () => {
  if (date.getTomorrow() ===  "1") {
    // that's the last day
   doSomeTasks()
  } 
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
crontask profile image
Info Comment hidden by post author - thread only accessible via permalink
Crontask.io

Hey! You may want to check our new platform to schedule and execute NodeJS scripts without a dedicated server or VPS at: crontask.io

Collapse
 
imshivanshpatel profile image
SHIVANSH PATEL

Nicely explained 🙂

Collapse
 
sohanurrahman0 profile image
Sohanur Rahman

If for scaling purpose i run my application in multiple server with multiple instances....How do i ensure that only one instance run the scheduled job?

Collapse
 
thesameeric profile image
Eric O Okiti

I was faced with a similar situation. What I did is I added all the jobs to a queue. I made 2 queues one for pending job and another for on-going jobs. when a job is being ran in an instance, it's moved to the ongoing queue so other instances pick tasks from the pending queue. You can use AWS simple queue service (SQS) to implement the queues.

Some comments have been hidden by the post's author - find out more