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:

CharacterDescriptorAcceptable values
1Minute0 to 59, or * (no specific value)
2Hour0 to 23, or * for any value. All times UTC.
3Day of the month1 to 31, or * (no specific value)
4Month1 to 12, or * (no specific value)
5Day of the week0 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 stringDescription
30 * * * *Execute a command at 30 minutes past the hour, every hour.
*/5 * * * *Execute a command every five minutes.
0 0 * * 1-5Execute 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 * * 0Execute a command every Sunday

NodeJS cron job

We need to install node-cron package first.

npm install node-cron

After installation, let’s do setup:

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.