As I am building website using node js and mongoose i need one hint of help that how i can automatically insert data in mongoose node js at certain time. Example at end of every month my data current data should automatically be stored in mongoose data base.
You can use node-cron to perform any CRON operation in node js.
https://www.npmjs.com/package/node-cron
Example:
var cron = require('node-cron');
/* CRON JOB Scheduled to daily at 12AM */
cron.schedule('0 0 12 1/1 * ? *', () => {
// Add your API/Logic here to insert data in mongoose using node.js
});
CRON generator
Related
I'm trying to send an email to the user periodically(daily, weekly, monthly) based on their preference from my nodejs application using node-cron. Here, user can edit/change their mail preference(weekly, daily..etc). so when they do, the cron expression gets updated to match their preference from the backend.
However, the previous preference still getting triggered, I believe that we have to destroy the previous job. how to do it?
Is this the right approach for my problem? or Do I need to store their preferences in database and triggered the mails manually based on the date?
This is how you should do it with node-cron :
const cron = require('node-cron');
const task = cron.schedule('* * * * *', () => {
console.log('stopped task');
}, {
scheduled: true
});
task.start();
task.stop();
task.getStatus(); // get you the status, so for every user check it and then restart it.
task.destroy(); // it will kill the job
It doesn't give any ID, but you can check the processID and store it anywhere.
You can check here for documentation.
I am using cron jobs to reset a particular field back to zero let's call it a streak I am trying to reset current streak of a user. so for that I am running a cron job at 11:59 to reset the data if user doesn't perform a particular task,But it's running according to UTC time. I want it to run according to users timezone who is using the application. Is it possible to run it according to different timezone or anyone could suggest any other way to do so.
You should set the time with a lib like http://momentjs.com/timezone/docs/.
var a = moment.tz("2013-11-18 11:55", "America/Toronto");
or
You should try CronJob npm package
new CronJob(
targetTime,
async function () {
await donsomething
},
null,
true,
time_zone
);
My current database structure looks like this,
Which basically has a mobile_users table and and a top 100 table which will be the leaderboard.
Im trying to figure out how to write a cloud function that executes every minute that updates/populates the top100 table with the userid, earned_points from mobile_users and sort it by earned_points.
Should i add a rank field on this table or is there a way to order the table from asc/desc order based on mobile_users?
My current function looks like this
exports.dbRefOnWriteEvent = functions.database.ref('/mobile_user/{userId}/{earned_points}').onWrite(event => {
var ref = admin.database().ref("/top100");
ref.orderByChild("earned_points").once("value", function(dataSnapshot) {
var i = 0;
dataSnapshot.forEach(function(childSnapshot) {
var r = (dataSnapshot.numChildren() - i);
childSnapshot.ref.update({rank: r},function(error) {
if (error != null)
console.log("update error: " + error);
});
i++;
});
});
});
I have yet to figure out how to tell the cloud function to execute every minute. I am having trouble structuring these type of queries.
My function is also failing to populate the the top100 table with those 3 current users. I would appreciate if someone could point me in the right direction.
Create a http request function that will do your business.
Then use cron-job to call your http firebase function every minute : cron-job
Maybe you can have two root nodes in your database. One like the above and a second node that is called leaderboard.
That second node can be an array where the index reflects the rank and the name reflects the score.
Leaderboard
|-- [0]
|-- score: 5000
|-- uid: 4zzdawqeasdasq2w1
|---[1]
|-- score: 4990
|-- uid: 889asdas1891sadaw
Then when you get a new score, you update the user's node and then also update the leaderboard. Then you just grab the uid and look up the name from the user's node.
Like the other posters said, use a HTTP Firebase Cloud Function and a chron job.
However I would recommend you use a chron job just to keep the cloud function alive (look up cold start firebase functions), but also make a fetch request to trigger the cloud function from the front-end everytime a user plays the game and generates a score. Otherwise if you get 10 plays per minute and it only updates once a minute, that will not be great user experience for the players who expect a real time leaderboard.
I am trying to update a database field on a MongoDB collection using Meteor at an exact time -- say 12:00 AM every Monday.
How should I go about doing this?
I am trying matching the day of the week and the exact time number but I can't seem to make it work for the server to do this more than once without using a loop that will make the website freeze.
If you can install a cron-job npm module, like: npm install cron, than you could set up a cron job with a Monday-only pattert, to call your db update code.
var CronJob = require('cron').CronJob;
var job = new CronJob('00 00 12 * * 1', function() {
/*
* Runs every weekday Monday at 12:00:00
*/
}, function () {
/* DB update code */
}
);
Docs available at https://github.com/ncb000gt/node-cron, if you need to fine tune your cron pattern or other options.
I'm implementing a "lowest bid auction" system. The users will set a base price, a price drop amount and a price drop interval. For example if an user set base price = 1000$ , price drop amount = 100$ , price drop interval = 1 hour, after 3 hours the price will be 700$, after 3.2 hours the price will still be 700$, after 4 hours it will be 600$...
These prices are stored into a mongodb database and need to be queried, so calculating current prices in node.js after the database querying gets really expensive. Is there a way to tell mongodb to update each document at a given time interval? Should I implement a node.js microservice that keep track of all these timers, and updates the documents when needed?
In practice these times will be actually big ( hours usually ), but I want to keep track of a lot of them.
Thank You,
Matteo
If you're using nodejs you could use Agenda to do this: https://github.com/rschmukler/agenda
so you'd define a task to reduce the prices of all your items:
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({db: {address: mongoConnectionString}});
agenda.define('reduce prices', {priority: 'high', concurrency: 1}, function(job, done) {
// .. do your db query to reduce the price here
done(); // dont forget to call done!
});
and then invoke it once an hour:
agenda.on('ready', function() {
agenda.every('60 minutes', 'reduce prices');
agenda.start();
});
And that's it. If you're using express and put this in your express app then you don't need to run a separate cron task - however this query will run on the same process as the rest of your application, so depending on how many "product" objects you're reducing prices for, this may or may not be an issue.