Automation Techs For Productivity And Fun

How To Repeat Node.js Tasks On Windows Without Using Task Scheduler


Using the Task Scheduler is the standard way to execute programs repeatedly on Windows.

But there is a problem that you have to save your Windows account if you want to execute the task when you're not logged in, and you have to remember to update your account when changing your password. If you forget to update, the task will try to login with your old account, and you may get locked out from Windows.

I've experienced this last day, searched for a better way to repeat my tasks.
I mainly write automation programs with Javascript for Node.js, and the best way I found, is to use "node-cron" an "PM2".

https://www.npmjs.com/package/node-cron

http://pm2.keymetrics.io/

"node-cron" is a Node.js library that keeps your program process running, and executes the specified function according to schedule settings.
You can set the schedule with crontab syntax.

"PM2" is a popular process manager for Node.js.
We need it to start our program at Windows startup.

Usage Example

First you need to install node-cron and PM2.

npm install --save node-cron

npm install -g pm2

Also you need an additional PM2 plugin to execute programs on Windows startup.

npm install -g pm2-windows-startup

You can find the PM2 document for startup here.

https://pm2.io/doc/en/runtime/guide/startup-hook/

Next, create a script for node-cron.

Let's say you created a Node.js program named "exampletask.js" with a exported function "main()", and you want to execute it on 9:00 AM every day.

A script for node-cron would be like this:



If you want to run it without using PM2, you can just run it as a Node.js program.

node exampletask_cron.js

You would see the program process keeps running, and executes your "main()" function at 9:00 AM.

The next step is to save the program as a PM2 process.
The next command adds "exampletask_cron.js" to the PM2 process list, and starts it as a PM2 process.

pm2 start exampletask_cron.js

Run the command below to check your PM2 process list.

pm2 ls

Next, save your PM2 process list.

pm2 save

Then set your process list to start on Windows startup.

pm2-startup install

For more information to custom settings, check out the PM2 document.

https://pm2.io/doc/en/runtime/overview/

This is all you need to do to schedule your Node.js program.
You don't have to worry about updating your login account when changing Windows password anymore.

Share:

Search This Blog

Labels

Generate Data For Testing With PostgreSQL

When developing a software using PostgreSQL database as storage, the function "generated_series" is very useful to create data ...

Powered by Blogger.

Labels

Recent Posts