nodejs setTimeout not working when called from cron job - node.js

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.

Related

Vanilla NodeJS Cron Job?

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)

Bukkit/Spigot - How to wait until BukkitRunnable is finished

In my onDisbale() method in my Main class I have a loop which creates and starts new BukkitRunnables.
I'm getting a error in console: org.bukkit.plugin.IllegalPluginAccessException: Plugin attempted to register task while disabled I need to somehow wait in my onDisable() method until all the BukkitRunnables I create in the loop are finished. How to do that?
My code looks like this:
#Override
public void onDisable() {
for (Player p : Bukkit.getOnlinePlayers()) {
new PlayerDataSaverRunnable().runTaskAsynchronously(this);
}
}
The onDisable method is the very last thing that gets called before your plugin is disabled and the server shuts down. So, as the error message says, you unfortunately can't schedule any new tasks in the onDisable function.
You mentioned in a comment that you were trying to write to a file in the plugins folder, and under normal circumstances you'd want to do that asynchronously. But, because onDisable only ever gets called when the server is shut down (or when the entire server is reloaded with /reload), it's perfectly fine to run code here that blocks the main thread and could potentially take a few seconds to run — in the case of a shutdown, by the time this method gets called, all the players will have already been kicked off the server, and so there's no "lag" to complain about. If your plugin is super advanced and has to save a bunch of stuff, I don't think any server owners would complain even if it took 10 or so seconds to disable.
Of course, you would have to be saving something crazy for it to take a whole 10 seconds to save. More than likely, most files will save in just a few milliseconds.
If you're really dead-set on disabling the plugin as fast as possible, you might consider having some async task that runs every 5 minutes or so and auto-saves the files. Then, in onDisable, you could only save files that changed since the auto-saver was last run. That's a good practice anyways, just incase the server crashes or the power goes out and the onDisable method doesn't get a chance to run. But, then again, I would still recommend that you save everything in the onDisable method (that's what I do for all of my plugins, as well), even if it will take a few seconds and block the main thread, just so you can be 100% sure that everything gets saved correctly.

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

Running setTimeout and showing log in terminal

I am trying to show the the log using below code in the terminal, but it is only showing one time, what is the wrong in the code ?
I created a file time.js with below code
setTimeout(function() { console.log("setTimeout: It's been one second!"); }, 1000);
and running the code in terminal like this
node time.js
the output is given below
Apples-MacBook-Pro:s3 apple$ node time.js
setTimeout: It's been one second!
Apples-MacBook-Pro:s3 apple$
while I am expecting setTimeout: It's been one second! log every minute
You should use the setInterval method instead:
setInterval(function() { console.log("setInterval: It's been one second!"); }, 1000);
However, beware that this code is dependent on the event loopback and if you have code that occupies the event loopback for too long, this code may not execute every second as you ideally want it to.

how can I remove/delete data from server node.js using interval time/ settimeout?

hi I'm trying create chat using node.js
I see example in http://chat.nodejs.org/
I have tried it and it works but how can I remove/delete data from server using interval time like in javascript without have to restart node.js/ terminal prompt?....
example:
time:
17:14
17:12
16:13
15:11
14:17
function del(){
if(time<timenow-1000){delete time;}}
setInterval("del()",10000);
I want to delete data less than two hours ago every one hours using interval time...thanks
First off, I would highly recommend against using the setInterval overload you are using that takes an eval string. Instead, always use the version that takes a callback. For example:
setInterval(1000, function () {
// do something
});
Take a look at the source and you will see that messages are stored in the messages array:
https://github.com/ry/node_chat/blob/master/server.js
Your function just needs to inspect this array and remove messages whose timestamp is older than your desired date. For example:
setInterval(1000, function () {
while (messages.length && messages[0].timestamp < someTime) {
messages.shift();
}
});
This will keep removing the oldest message while it is older than someTime, which is a time you will need to specify.

Resources