Vasuki Hebbar
Vasuki Hebbar

Reputation: 51

How to schedule the node js script to run automatically on windows?

This script

0 0/3 * * * node test.js

is used to schedule the job in Ubuntu, How to set the same way in Windows using node-schedule npm package?

As a work around , have scheduled the script in Task Scheduler:

cmd /c c:\node\node.exe c:\myscript.js

I want to to know how this can be done in node-schedule npm package.

Upvotes: 2

Views: 5784

Answers (2)

Temuujin Dev
Temuujin Dev

Reputation: 921

You can use 'cron' package for schedule functions on nodejs - https://www.npmjs.com/package/cron

According it's docs

Cron is a tool that allows you to execute something on a schedule. This is typically done using the cron syntax. We allow you to execute a function whenever your scheduled job triggers.

Usage example

const CronJob = require('cron').CronJob;

const exampleJob = new CronJob(`*/2 * * * * *`,()=>{
    console.log("You will see this message every 2 seconds",new Date().getSeconds());
});

exampleJob.start();

for addition if you not familiar with cron schedule expressions(cron syntax) that web will help you get right expression https://crontab.guru/

Upvotes: 2

user9572013
user9572013

Reputation:

From https://npmjs.org/package/node-schedule:

Execute a cron job every 5 Minutes = */5 * * * *

So (according to the NodeJS docs) you can use the child_process npm module to run the script.

Like this:

const { spawn } = require('child_process');
const schedule = require('node-schedule');

schedule.scheduleJob('*/5 * * * *', function() {
  spawn('node', ['test.js']);
});

Upvotes: 2

Related Questions