I want a function that will decrement a value automatically everyday - node.js

I'm working on an web application using NodeJS and MongoDB/Mongoose, and I want to create a method that everyday, at some hour, will automatically decrement a value from a field by 1.
Can you help me, please?

Use setInterval() If you just want to run it every day at the same time.
setInterval(() => {
// your code
}, 86400000);
where 86400000 is the amount of milliseconds in a day.
If you want more control over the timing, I recommend using node-cron.
And of course your program needs to run on a server for it to run forever. Or you could leave your computer on forever, but that wouldn't be quite ideal.

Related

Python: run a function at set interval while program runs

I have a program that will be running 24/7 (assuming no server crashes). The program waits for users of a chat channel to issue commands, then it does several things based on the command issued and user permissions. This program will use and update data from Tuesday 10AM till next Tuesday 9AM, at which point, at 9AM, it will need to wipe the data and start over for the next week cycle.
I'm having trouble finding a way to implement the weekly reset though. I could restart the program every week, but was wondering if there is a way to run a background process that executes a function at a set interval (one week in this case). I was thinking of using a thread to keep track of time, and when a week has passed, have the thread execute the data wipe function. But wouldn't this be an unnecessarily expensive operation? Having a thread running at all times keeping track of passing time seems like a brute force solution.
I would greatly appreciate some pointers on how to go about doing this.
from datetime import datetime
next_wipe = get_next_wipe_datetime() # typically Tue. 9am
...
cmd = read_chat_channel()
if datetime.now() > next_wipe:
next_wipe = get_next_wipe_datetime()
do_wipe()
process(cmd)

Updating action on express server every short peroid of time

I'm currently developing a gambling website built on top of Ethereum blockchain. Since recording all the bets made by a gambler is very complex (because they can make a bet without even visiting the website, by interacting directly with the blockchain) I came to conclusion that I need a function on my server that will run every 0.5 - 1 minute and download all the new bets that came up from the blockchain and shadow them in my database (yes I need to have them in my database as well).
I am not experienced too much with all this backend stuff, I've read somewhere that I could use setInterval(30 seconds) function on the server and run it on the server start. But is this a real option? Do people even do things like this? Won't an infinite function running every 30 second just clog up the whole server?
I've done similar a number of times with no issue. Events will just be queued and run as appropriate. However, one thing to be wary of:
const timeout = 1000;
setInterval(() => {
// some process that takes longer than timeout
}, timeout);
When you write something like this, setInterval will run again after the timeout period even if the first operation hasn't completed yet. THIS can easily lead to you blocking your thread. Instead, I prefer to use setTimeout to achieve this:
const timeout = 1000;
const withTimeout = () => {
// some process that takes longer than timeout
setTimeout(withTimeout, 1000);
}
This way, your second invocation of withTimeout is only queued up AFTER the first execution is run. With this mechanism, you don't get your operations strictly every timeout period, but rather timeout AFTER the last one.

How to frequent compare 2 dates for a huge set of objects (as cronjob) - nodejs

My system has tasks that has a deadline (as date stored in the database) differ from task to another, I want to check frequently for these tasks if they exceed their deadline (basically with the current date I guess), and if so send a notification or execute a function
How can I make this function to be executed as cronjob or as it is without the help of cronjob.
I want to do this without making heavy load on the server
I'm using Express and sequelize as ORM
I did see node-cron as scheduler but i don't have the idea to implement something like this
I would appreciate any help :)
You can use later package for this tasl like that:
https://github.com/bunkat/later
var later = require('later');
later.date.UTC();
const DEDLINE_SCHEDULE = later.parse.text('every 1 min');
later.setInterval(createNotificationJob(), DEDLINE_SCHEDULE);
function createNotificationJob() {
// check are tasks exceed their dedline
}
and then every 1 minute you can check that if tasks exceed their deadline and send notification.

Scheduling Tasks in Node.js Using Timers instead of Scheduled Cron Jobs

This is my objective:
5 minutes after the last document update, I want to execute a one-time task
So this is what the flow of actions will look like:
User updates document - timer is started and counts down from 5 minutes
If user updates the same document again and the previous timer (identified by the document._id) is running still, reset that timer back to 5 minutes and repeat countdown
When timer has elapsed - the one time task is executed
I have not done something like this before and I am at a loss at where to begin.
I can hook into document changes easily using methods available in Mongoose (i.e. on save, do func to setup or reset timer)
However, I cannot figure out the way to:
create a timer that waits 5 minutes - then executes a task
making the timer accessible so that I can reset the timer
making the timer accessible so I can add extra variables which will be used in the funtion when timer has elapsed
I've investigated Cron jobs but they seem to tasks that schedule at the same time everyday.
I need a timer that delays a task, but also the ability to reset that timer, and add extra data to the timer.
Any hints appreciated.
This is the solution I managed to complete up with.
First of all, it's worth noting that my original assumptions are correct:
Cron jobs are great for repetitive, tasks that are scheduled at the same time everyday. However, for tasks that are created on the fly, and have a countdown element, then cron jobs isn't the right tool.
However, enter node-schedule (https://www.npmjs.com/package/node-schedule)
Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute).
The use of timers is really what these, on-the-fly tasks need.
So my solution looks like this:
var schedule = require('node-schedule'),
email_scheduler = {};
email_scheduler["H1e5nE2GW"] = schedule.scheduleJob(Date.now() + 10000, function(){
console.log('its been a total of 10 seconds since initalization / reset.');
});
var second_attempt = schedule.scheduleJob(Date.now() + 5000, function(){
console.log("5 seconds elapsed from start, time to reset original scheduled job");
email_scheduler["H1e5nE2GW"].cancel();
email_scheduler["H1e5nE2GW"] = schedule.scheduleJob(Date.now() + 10000, function(){
console.log('its been a total of 10 since last one seconds.');
});
schedule.scheduleJob(Date.now() + 5000, function(){
console.log("it's been another 5 seconds since reset");
});
});
My thinking (though not yet tested) is that I can create a singleton-like instance for the email_scheduler object by creating a node module. Like such:
// node_modules/email-scheduler/index.js
module.exports = {};
This way, I can access the scheduleJobs and reset the timers in every file of the node application.
You can use events for that. call a event with some parameter and before your task add sleep and exec your task. But add sleep or settimeout is not a good idea in nodejs.
I had the same puzzle but I ended settling on the javascript native functions.
function intervalFunc() {
//inside this function you can request to get the date and time then decide what to do and how to do it
autogens.serverAutoGenerate();//my function to autogenerate bills
}
setInterval(intervalFunc, 1000);//repeat task after one seconds
Adding the code at the index file or entry file of your node js application will make the function repeatedly execute. You can opt to change the frequency depending on your needs. If you wanted to run the cronjob three times a day, get the number of seconds in 24 hours then divide by 3. If you wanted to run the job on a specific hour, by using the new Date(), you can check to determine if it is the right hour to execute your event or not.

sailsjs & laterjs task scheduling, initialization.. poll every x or sleep for x?

I am building an open sourced nodejs powered sprinkler system which will run on the raspberry pi and work with the OpenSprinkler Pi.
I am using:
sailsjs 0.9.3
laterjs - for schedule interpretation and maths
i created an issue awhile back on bunkats repo asking for him to explain this to me.. https://github.com/bunkat/later/issues/19
The end result will be a REST api interface between rpi and whatever front-end you decide to develop for. web/mobile/cli .. etc.
The way the scheduling component will work is values will be posted to the url /programs with a zone id, name, intial status (false), and a plain text human readable schedule phrase such as: every 12 hours starting on the 6th hour before 10 minutes (06:00 & 18:00 for 10 mins).
This schedule will be parsed, and stringified and stored in db as such:
{\"schedules\":[{\"h\":[6,18],\"m_b\":[10]}],\"exceptions\":[],\"error\":-1}
The other values are cleaned and stored as they were entered.
My question is:
how should I go about finding these schedules and determining their run time/date? I've got the scheduling part, and the run time down and working (run for 10 mins). I'm struggling with the theory behind efficiently retrieving the schedules though.
My initial thought was to have a interval every 1 mins poll the db...
setInterval(function(){
//get programs from db
//iterate through programs
//enable programs which start now?
}, 60000);
But this seems kind of illogical. I suppose that when the schedule is created a setInterval or setTimeout is created with the appropriate scheduling info.. but what happens if the rpi loses power, or those could eat up a bit of memory having all of these intervals hanging out there..
how will it handle existing schedules already in the db?
open source repo
of what i have so far (not much other than the creation api/models/Programs.js) is here:
https://github.com/RelativeMedia/nodesprinkler.git

Resources