Schedule Node.js job every five minutes - mongodb

I'm new to node.js. I need node.js to query a mongodb every five mins, get specific data, then using socket.io, allow subscribed web clients to access this data. I already have the socket.io part set up and of course mongo, I just need to know how to have node.js run every five minutes then post to socket.io.
What's the best solution for this?
Thanks

var minutes = 5, the_interval = minutes * 60 * 1000;
setInterval(function() {
console.log("I am doing my 5 minutes check");
// do your stuff here
}, the_interval);
Save that code as node_regular_job.js and run it :)

You can use this package
var cron = require('node-cron');
cron.schedule('*/5 * * * *', () => {
console.log('running a task 5 minutes');
});

This is how you should do if you had some async tasks to manage:
(function schedule() {
background.asyncStuff().then(function() {
console.log('Process finished, waiting 5 minutes');
setTimeout(function() {
console.log('Going to restart');
schedule();
}, 1000 * 60 * 5);
}).catch(err => console.error('error in scheduler', err));
})();
You cannot guarantee however when it will start, but at least you will not run multiple time the job at the same time, if your job takes more than 5 minutes to execute.
You may still use setInterval for scheduling an async job, but if you do so, you should at least flag the processed tasks as "being processed", so that if the job is going to be scheduled a second time before the previous finishes, your logic may decide to not process the tasks which are still processed.

#alessioalex has the right answer when controlling a job from the code, but others might stumble over here looking for a CLI solution. You can't beat sloth-cli.
Just run, for example, sloth 5 "npm start" to run npm start every 5 minutes.
This project has an example package.json usage.

there are lots of Schedule package that would help you to do this in node.js . Just choose one of them based on your needs
following are list of packages:
Agenda,
Node-schedule,
Node-cron,
Bree,
Cron,
Bull

Related

is it possible to use setTimeout() in firebase cloud functions?

i am wondering if it is possible to use setTimeout() in cloud functions
let millisecond = (day *24*60*60*1000) + (hour* 60*60*1000) + (min *60*1000) + (second *1000);
setTimeout(() => {
admin.firestore().doc("timer/" + chatroom).set({
"millisecond":millisecond,
"username":username,
"tousername":tousername,
"day":day,
"min":min,
"second":second,
"hour":hour,
}, millisecond);
if not possible is there a way to accomplish this idea ?
also am i billed as much as the function is active?
thank you
Using setTimeout in a Cloud Function is possible, but keep in mind that:
a function can run at most 9 minutes (1st generation) or 60 minutes (2nd generation) (see docs)
you pay for the entire time a function is active this way
So if you need to wait for significant time (I usually use 30s as a threshold for this), consider using another mechanism to delay operations such as scheduling a callback with Cloud Tasks.

Flutter Local Notifications show notification every 72 hours

I am trying to send out notifications every 72 hours. I am using the flutter_local_notifications package. I know I can periodically show notifications but as far as I can see it is limited to these options:
/// The available intervals for periodically showing notifications.
enum RepeatInterval {
/// An interval for every minute.
everyMinute,
/// Hourly interval.
hourly,
/// Daily interval.
daily,
/// Weekly interval.
weekly
}
Is there any way to achieve the 72h interval? I couldn't find anything on this. Let me know if you need any more info! Any help is appreciated!
you can try this :-
fltrNotification = new FlutterLocalNotificationsPlugin();
var scheduledTime = DateTime.now().add(Duration(hour : 72));
fltrNotification.schedule(1, "Times Uppp", task,
scheduledTime, generalNotificationDetails);
always this approach works
make your own copy of package
modify it 😊
1.make your own copy
you can easily copy the package file to your project . and use it like this (flutter doc)
dependencies:
plugin1:
path: ../plugin1/
if you prefer you can fork project and use it like below
dependencies:
plugin1:
git:
url: git://github.com/flutter/plugin1.git
2.modify it 🛠
for your question you can change the value of Daily interval to (3 * Daily interval)
I found this part of code (android - ios)
I would use the flutter cron package if I were you: cron package on pub.dev
It allows you schedule a cron job which is simply a task that runs every x seconds or days, months...
For your example:
fltrNotification = new FlutterLocalNotificationsPlugin();
final cron = Cron();
// Schedule a task that will run every 3 days
cron.schedule(Schedule.parse('0 0 */3 * *'), () async {
// Schedule a notification right now
fltrNotification.schedule(1, "Times Uppp", task,
DateTime.now(), generalNotificationDetails);
print('every three days');
});
If you want to change the frequency, cron is very flexible and you can do pretty much any frequency, the cron syntax is pretty straightforward and their are some websites online that allow you to simply generate it.
There are, of course, several ways to use cron to do what you want. You could schedule a notification for the next 72 hours every 72 hours, refreshing every 24 hours, whatever seems better to you.
(I used part of Piyush Kumar's answer for this example by the way, and updated it to use cron)

Play Framework - Schedule a task at precise time [duplicate]

This question already has answers here:
scala - How to run a task every day a 11PM
(2 answers)
Closed 6 years ago.
I'm doing a Scala - Play application and I want to schedule a task to sending mail everyday at 3 A.M, so I create a class for that but i'ts not working:
class ManageSendInvalidateDaemon #Inject() (app: Application, emailSender: EmailSender, mailer: MailerClient) {
Akka.system(app).scheduler.schedule(
scala.concurrent.duration.Duration.create(20,TimeUnit.SECONDS),
scala.concurrent.duration.Duration.create(60, TimeUnit.SECONDS),
new Runnable(){
override def run()={
//Function to send the mail
}
}
);
};
I think the problem is here:
scala.concurrent.duration.Duration.create(20,TimeUnit.SECONDS),
scala.concurrent.duration.Duration.create(60, TimeUnit.SECONDS),
I don't really understand what it's the use of these 2 lines
That will not work as you expect. Akka scheduler just lets you specify the recurrency of the task, but not the day, hour etc when it will run (ex: you can tell it to run a task every 10 minutes, but not run this at 15:30 each Monday).
Those two lines instruct Akka to run that task every 60 seconds, and run the first time 20 seconds after you define it (so if the schedule call is executed at 12h30m that task will run the first time at 12:30:20 and then 12:31:20, 12:32:20, etc).
To overcome this, you just need to run a task periodically (in your case, each minute for example), and check the current hour. If it is 3AM send those emails (and eventually store anywere that this task was executed).
Another option is to use something like akka-quartz-scheduler, that lets you specify that type of scheduling
I had the same problem. So I created a method to calculate how much time from now until the time I want to run my
schedule = Akka.system().scheduler().schedule(
Duration.create(nextRunTime(), TimeUnit.MILLISECONDS),
Duration.create(DAY_IN_MS, TimeUnit.MILLISECONDS),
...,);
The nextRunTime() method calculates how much time in milliseconds will be until the next 3 AM and after that I set an interval of one day (DAY_IN_MS)
private int nextRunTime() {
String runTimeValue = "03:00";
LocalTime now = new LocalTime();
LocalTime runTime = new LocalTime(runTimeValue);
int timeUntilRun;
if (runTime.isAfter(now)) { // From now until the run time
timeUntilRun = runTime.getMillisOfDay() - now.getMillisOfDay();
} else { // From now until midnight, plus from midnight until the run time
timeUntilRun = DAY_IN_MS - now.getMillisOfDay() + runTime.getMillisOfDay();
}
Logger.info("nextRunTime(): next run in " + timeUntilRun + " ms");
return timeUntilRun;
}

setInterval with a variable interval

I would like an api call to be done immediately, then after 1sec, then 2sec, etc in incrementations of 1 sec up to 10.
I tried something like this:
Meteor.startup ->
counter = 1000
Meteor.setInterval (->
Meteor.call "call_url", url, (err, result) ->
...
if counter < 10000
counter += 1000
console.log counter
), counter
While my counter is incremented, the log is done exactly every seconds, which means that the setInterval doesn't keep track of the value.
The only way I see to handle this would be having 9 setTimeout to call the api at different times, then a Meteor.setInterval starting after all the timeouts... Sounds very ugly.
Any suggestions on how to do this in a clean way? It's important for the user to see frequent updates when he just connects to the page, but if he decides to let it open for a while, there is no need to perform that api query so often.
A more general solution (and scalable in the future for CoinsManager) is to use a queuing package that supports scheduling events in the future. I've looked at a bunch of background task management for Meteor, and queue supports scheduling.
Not quite clear what you are asking and there are probably a lot of ways to generate the intervals you want.
In javascript it might look like this:
var doStuff = function(){...};
var intervals = [ 1000, 3000, 6000, 10000, 15000, 21000, 28000, 36000, 45000, 55000 ];
doStuff(); //run immediately
intervals.forEach( function( interval ){
Meteor.setTimeout( doStuff, interval );
});

Quartz.Net - delay a simple trigger to start

I have a few jobs setup in Quartz to run at set intervals. The problem is though that when the service starts it tries to start all the jobs at once... is there a way to add a delay to each job using the .xml config?
Here are 2 job trigger examples:
<simple>
<name>ProductSaleInTrigger</name>
<group>Jobs</group>
<description>Triggers the ProductSaleIn job</description>
<misfire-instruction>SmartPolicy</misfire-instruction>
<volatile>false</volatile>
<job-name>ProductSaleIn</job-name>
<job-group>Jobs</job-group>
<repeat-count>RepeatIndefinitely</repeat-count>
<repeat-interval>86400000</repeat-interval>
</simple>
<simple>
<name>CustomersOutTrigger</name>
<group>Jobs</group>
<description>Triggers the CustomersOut job</description>
<misfire-instruction>SmartPolicy</misfire-instruction>
<volatile>false</volatile>
<job-name>CustomersOut</job-name>
<job-group>Jobs</job-group>
<repeat-count>RepeatIndefinitely</repeat-count>
<repeat-interval>43200000</repeat-interval>
</simple>
As you see there are 2 triggers, the first repeats every day, the next repeats twice a day.
My issue is that I want either the first or second job to start a few minutes after the other... (because they are both in the end, accessing the same API and I don't want to overload the request)
Is there a repeat-delay or priority property? I can't find any documentation saying so..
I know you are doing this via XML but in code you can set the StartTimeUtc to delay say 30 seconds like this...
trigger.StartTimeUtc = DateTime.UtcNow.AddSeconds(30);
This isn't exactly a perfect answer for your XML file - but via code you can use the StartAt extension method when building your trigger.
/* calculate the next time you want your job to run - in this case top of the next hour */
var hourFromNow = DateTime.UtcNow.AddHours(1);
var topOfNextHour = new DateTime(hourFromNow.Year, hourFromNow.Month, hourFromNow.Day, hourFromNow.Hour, 0, 0);
/* build your trigger and call 'StartAt' */
TriggerBuilder.Create().WithIdentity("Delayed Job").WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever()).StartAt(new DateTimeOffset(topOfNextHour))
You've probably already seen this by now, but it's possible to chain jobs, though it's not supported out of the box.
http://quartznet.sourceforge.net/faq.html#howtochainjobs