User defined cron job node js - node.js

I have one requirement where i need to run cronjob/scheduler in node express, where user can set/update scheduler time.
I have explored cron module from npm , however i can not set dynamic cron scheduling.
Please find the code below
new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
In above code * * * * * * will be dynamic or set by user.
Please suggest solution. Thanks in advance.

When the user sets the cron parameters, in that api call firstly stop the exisiting CronJob and then create new immediately after that using user entered values.
There is stop parameter mentioned in API here
https://www.npmjs.com/package/cron

Related

Cron job in strapi V3 does not get triggered when a method from strapi services is called

config/functions/cron.js
async function logger() {
console.log("Hello, Im Async");
}
module.exports = {
'*/10 * * * * *': async () => {
console.log("Before);
await strapi.services.collectionName.someMethodName();
console.log("After);
},
'*/10 * * * * *': async () => {
await logger();
},
};
In the example above logger gets called properly. But someMethodName doesn't get called at all. Before and After are also not printed. I dont know what is wrong and how to check it.
Same code works in staging site but not on production server.
I dont understand what is happening and how to solve this.
Does anyone know a solution to this?
Thanks!
Found the solution. Posting it here so that it will help someone else in the future.
Time format for both of the cron tasks is the same. When I checked the list of active cron in the strapi config; there was only one cron task available. It seems that as the key for the export was same, second entry was overriding the first one. When I wrote diff time formats for diff task, list of active cron jobs showed all the cron tasks.
Below commands will help you check the list of active cron tasks.
npm run strapi console
const strapi = require('strapi');
strapi().config

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.

DSL for enabling the Build periodically in jenkins

I know how to do it using polling, with
triggers
{
scm("H/15 * * * *")
}
How do I specify the trigger to Build periodically instead?
Use cron to build periodically, as in:
triggers
{
cron("H/15 * * * *")
}
This will build every 15 minutes regardless of whether there are SCM changes.

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

Resources