Cronjob on the Node, is there?

Asked

Viewed 126 times

0

Hello, I am creating a system of tasks and notifications, it works like this: the user creates a task for the system to execute when it arrives at a given time, automatically, notifications are created in the database, one before executing, to remind the user of what it will do, and another one just in time to let you know that it’s happening.

I wonder if there is a way to run a script that keeps checking if there are tasks to be accomplished at that minute, and if there are, run, preferably on Node, my backend is all on Node.

  • yes. I have a Rest api

  • 2

    React is front-end, which Backend is using, it can be configured this ...?

  • Gee, mds kkk I missed. I’m beginner at it. It’s in Node

  • maybe it screwed up my research

  • Dude, your backend is in Node, I recommend using Agenda to check some information from time to time

  • Thank you very much Virgilio and Denis. I have another question, if you could help me, I would be grateful again. I have there in my server the PM2 running the API, so I put this cron job to run, I can create it within the project itself? Like, create it in a worker folder and run it via pm2?

  • 2

    You need to see if this cron job can send a request to your web api and with socket.io update your front ... that would be the initial logic

Show 2 more comments

2 answers

4


CRONJOB does not belong to languages, belongs to the operating system, create a JOB from a script just run in the terminal:

crontab -e
00 * * * * /usr/bin/node /home/usuario/foo-bar.js

And you could use these commands with the native API:

Could do something like:

var exec = require('child_process').exec;

exec('crontab -e && 00 * * * * /usr/bin/node /home/usuario/foo-bar.js', function(error, stdout, stderr){
   console.log(stdout);
});

I did not test, but it will probably work (the example is for linux servers, remembering to change folders according to locations)

To facilitate you can install via NPM the https://www.npmjs.com/package/cron

 npm i cron.

Example of basic cron https://www.npmjs.com/package/cron#Usage-basic-cron-Usage:

var CronJob = require('cron').CronJob;
var job = new CronJob('* * * * * *', function() {
  console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
job.start();

Note: Despite the example to suggest the Timezone, it would be better to work with UTC and study well on timezones, because many people use it in the wrong way.

0

I am using cron, to install just use npm and it is very simple to use, example:

const CronJob = require('cron').CronJob
const job = new CronJob('*/10 * * * * *', _ => {
    console.log(new Date(1591106980002).toString())
})

job.start()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.