Cron Job on TypeScript

typescriptimage.jpeg?w=2924

What is Cron?

Cron is a classic utility found on Linux and UNIX systems for running tasks at pre-determined times or intervals. These tasks are referred to as Cron tasks or Cron jobs. Use Cron to schedule automated updates, report generation, or check for available disk space every day and send you an email if it falls below a certain amount.

Basic formatting

The Cron time string is five values separated by spaces, based on the following information:

Character Descriptor Acceptable values
1 Minute 0 to 59, or * (no specific value)
2 Hour 0 to 23, or * for any value. All times UTC.
3 Day of the month 1 to 31, or * (no specific value)
4 Month 1 to 12, or * (no specific value)
5 Day of the week 0 to 7 (0 and 7 both represent Sunday), or * (no specific value)

The Cron time string must contain entries for each character attribute. If you want to set a value using only minutes, you must have asterisk characters for the other four attributes that you’re not configuring (hour, day of the month, month, and day of the week).

Let’s see some basic example:

Cron time string Description
30 * * * * Execute a command at 30 minutes past the hour, every hour.
*/5 * * * * Execute a command every five minutes.
0 0 * * 1-5 Execute a command on every day-of-week from Monday through Friday
15 16 1 * * Execute a command at 16:15 on day-of-month 1:
0 0 1 */6 * Execute a command every 6 months
0 0 * * 0 Execute a command every Sunday

NodeJS cron job

We need to install node-cron package first.

1
npm install node-cron

After installation, let’s do setup:

1
2
3
4
5
import cron from "node-cron";

cron.schedule("* * * * *", () => {
console.log(`this message logs every minute`);
});

And now, you can start using cron-jobs in your project.
Happy coding, enjoy.