Vanilla NodeJS Cron Job? - node.js

I want to do something in node at, say, midnight each day.
I see a lot of stuff pointing me to node-cron, and I see this article configuring a docker container to execute a script per a crontab
I want to 1. not use any external packages and 2. keep the script being executed inside the server code itself (i.e. I couldn't have the docker container execute some other file on a schedule)
The use case is I want to update a cache on the server every day around midnight, and then, at more frequent intervals, use that cache for various things.

You can use setInterval to run the code every hour and check if it's around midnight
setInterval(() => {
if (new Date().getHours() === 0) {
// do stuff
}
}, 1000 * 60 * 60 * 60)

Related

Cron task runs for only 1.5 min and stops

The task loads PHP code that updates the price and availability of products in an online store.
After checking the database, I found that the process aborts after about 1.5 min without updating all products.
How can I extend the time?
Platform OpenCart 2.3.
A cron task: wget -q --spider https://mysite.om/index.php?route=extension/module... Is it correct?
Check the php.ini
ini_set('max_execution_time', 300); // 300 seconds = 5 minutes
ini_set('max_execution_time', 0); // 0=NOLIMIT
But on the most shared servers this function does not work it is not allowed.

Repeatable jobs not getting triggered at given cron timing in Bull

I wanted to perform some data processing in parallel using Bull NPM and start processing each job at the given cron Time
const Queue = require("bull"),
/**
* initialize the queue for executing cron jobs
**/
this.workQueue = new Queue(this.queueOptions.name, {
redis: redisConfig
});
this.workQueue.process((job, done) => {
done();
this.processJob(job)
.then(data => {
global.logger.info(`successfully-executed-job ${job.id}`);
})
.catch(error => {
global.logger.error(`JSON.stringify(error)}-in-executing-job-${job.id}`);
});
});
// here I have included Unique JobId
this.workQueue.add({}, {repeat: { cron:"5 * * * *",jobId:Date.now()});
Any suggestions to achieve the same?
The issue is resolved now if you're facing the same issue make sure that you're referring to the correct timezone.
Cheers!!
I also faced this same issue. One thing to note with respect to the above code is that a Queuescheduler instance is not initialized. Ofcourse timezone also plays a crucial role. But without a Queuescheduler instance (which has the same name as the Queue), the jobs doesnt get added into the queue. The Queuescheduler instance acts as a book keeper. Also take care about one more important parameter "limit". If you dont set the limit to 1, then the job which is scheduled at a particular time will get triggered unlimited number of times.
For example: To run a job at german time 22:30 every day the configuration would look like:
repeat: {
cron: '* 30 22 * * *',
offset: datetime.getTimezoneOffset(),
tz: 'Europe/Berlin',
limit: 1
}
Reference: https://docs.bullmq.io/guide/queuescheduler In this above link, the documentation clearly mentions that the queuescheduler instance does the book keeping of the jobs.
In this link - https://docs.bullmq.io/guide/jobs/repeatable, the documentation specifically warns us to ensure that we instantiate a Queuescheduler instance.

How to run a node script automatically at specified intervals

I'm making a dating app. Every day at midnight I want 'new matches' to be randomly found and displayed to a user.
If anyone could give a give high level overview of how this would work I'd be really grateful?
If want to execute a Node task every midnight then Cron jobs is a powerful, yet simple tool that can help us get there. You can user Cron Package to achieve this in node.
You can add cron dependency using
npm install cron
You can modify following script
var CronJob = require('cron').CronJob;
var job = new CronJob('00 00 01 * * *', function() {
console.log('You see this message every day 01 AM America/Los_Angeles');
}, null, true, 'America/Los_Angeles');
Where you can replace console.log with the logic you want to implement the code that will find match for each users of app and replace timezone with yours.

Setup Heroku Scheduler job to email all users (Meteor/MongoDB)

Does anyone know if it's possible to make a Heroku Scheduler job that would send an email to all of my users once per day? I'm using Meteor and MongoDB.
I can see that the Heroku Scheduler can run a command such as "node somefile.js" but I can't seem to figure out how to make a connection to the mongodb in a file like this. Can I somehow tap into the DB without involving Meteor in this?
Any help would be appreciated!
I eventually found a package to do so: synced-cron. Basically, you need to setup a method in which use the package to fire a recurring job.
The package website also has a sample code:
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every 2 hours');
},
job: function() {
var numbersCrunched = CrushSomeNumbers();
return numbersCrunched;
}
});
Here you just need to replace the code in the job function to send out the email.
The job supports schedules like "every 5 minutes", "at 5:00pm", etc. The package relies on the text parser in Later.js to parse the schedule. You can refer to the Later.js doc.
Two different options.
The first is to use Heroku's scheduler,
In which you create a text file in your bin directory:
#! /app/.heroku/node/bin/node
var test = require('./jobToDo') //put your job in this file (jobToDo.js)
Now you don't have to put the job in another .js file, but it makes it easier to work with, rather than coding in a plain text file. (put again that is up to you)
The first line #! /app/.heroku/node/bin/node may be different for you depending on how your configuration is set up, depending on your OS and node/npm set up.
The second option is a cron style library. This will allow you to decide when you want your code to run.
This is pretty easy, and for me the preferred method.
var CronJob = require('cron').CronJob;
var fn = function(){
// Do Something
}
var job = new CronJob({
cronTime: "00 00 02 * * 1-5",
onTick: fn,
start: true,
timeZone: 'America/Los_Angeles'
});
You can look at documentation on github

nodejs setTimeout not working when called from cron job

I am writing a nodejs program, which needs to upload local sensor information to central database every 15 seconds. since the minimum cron interval is 1 minute, i am calling the the upload routine 4 times like this
function uploadToDatabase() { /* blah blah blah */ }
setTimeout(uploadToDatabase, 1*1000);
setTimeout(uploadToDatabase, 15*1000);
setTimeout(uploadToDatabase, 30*1000);
setTimeout(uploadToDatabase, 45*1000);
this function getting called as intended when i run this in command like like
node uploader.js
but when this is called from cron job this function uploadToDatabase never called?
Any idea why?
You don't need a cron job. Just run it in node and have a loop that executes every 15 seconds.

Resources