How to execute a function for each period of time? - javascript

I want a certain function to run every round hour. There is the solution of running an interval when it's a round hour but I often turn on and off my script and I don't want to have to run it exactly on a round hour.
I've tried looking through some npm modules and I found one but I had some issues with it. Does anyone have a solution?

No need for javascript! You have the perfect tool for that if you use linux!
Use cron:
$ sudo crontab -e
This will open a vim editor. Then add:
0 * * * * node /execute/your/script.js
(basically, it will run your code every hour on its minute zero)
More info
cron: https://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/

const HOUR = 1000 * 60 * 60;
function hourly() {
//....
setTimeout(hourly, HOUR);
}
setTimeout(hourly, HOUR - (new Date % HOUR));
Just calculate the next full hour when the server starts, and then shedule an hourly timer.
I admit that it might loose accuracy due to leap seconds :)

Related

Discord.js Status Time Elapsed

I am using Discord.js Node V12
I am currently trying to find out how to say time elapsed in the status to show how long the bot has been online. But i cannot find anyone who has asked or answered any of these questions
Well, you can use client.uptime to get the amount of time your bot has been online (since it last booted up) in milliseconds. You can then take those milliseconds and convert them into whatever unit of time you choose. Here's an example, converted to hours:
var uptime = client.uptime; //in milliseconds
var hours = uptime / 1000 / 60 / 60 ; //milliseconds -> seconds -> minutes -> hours
If you're referring to how long the bot has been up since the first time you ever started it up, that's an entirely different answer, and you would need to clarify further on that. But if you just want total online time elapsed since the bot was last offline, this is the answer.
If you are using this in a command, you can retrieve client from the message object, like so:
var uptime = message.client.uptime; //in milliseconds
var hours = uptime / 1000 / 60 / 60 ; //milliseconds -> seconds -> minutes -> hours
I do not know why you could not find the answer, if my understanding of your question is correct, because this information can be found easily on this website and on discord.js docs.
Relevant resources:
https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=uptime
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=client

How to schedule node-cron job every new month?

I am using node-cron package for scheduling node-cron jobs. I want to schedule an node-cron job which will run every new month.
for example:
My node-cron job should run at 1 September 2020 after that it should run at 1 October 2020 and and so on..!
Please help me out for the above issue.
Thanks in advance.
I've tested accepted answer's code and noticed that there is something off.
cron.schedule(* * 1 * *) will make code run every first day of the month, and every hour and every minute. This means if it is first day of month, code will run once every minute.
To correct this issue (and actually run once a month, not multiple times in one day) we change: cron.schedule(* * 1 * *) to: cron.schedule(0 0 1 * *) so code runs every first day, at 00:00.
Following this tutorial I believe you just have to do:
const cron = require("node-cron");
cron.schedule("* * 1 * *", function() {
// Do something
});
where:
cron.schedule("* * * 1 * *", function() { // Do something });
OR
cron.schedule("* * 1 * *", function() { // Do something });
NOTE : remember that the first * of the six * is optional

Node-scheduler how to set recursive condition

I want to run a background script every day at midnight after every 10 minutes.
It should run on 00:10, 00:20, and so on
What I have tried is.
schedule.scheduleJob("1 0-23 * * *", async () => {
})
What I want is to find a way to start this job at midnight and should be run after each 10 minutes
In your case schedule must be: */10 * * * * – run every 10th minute.
I'm not sure what you mean by starting at midnight. When it should finish then?
Update based on comment:
If you want to run it during the interval of 12 PM to 10 AM you'll need to specify the hour parameter. And it'll look like this: */10 0-10 * * * - every 10th minute past every hour from 0 through 10
start at 00:00:00
then at 00:10:00
then at 00:20:00
...
finish at 10:00:00
Hint: you can use crontab.guru to play with Cron formats.

How to schedule execute a part of script in perl once every hour while the rest is refreshing every minute

I have a Perl script that refreshes the web page every minute. Now I want to add some MySQL queries that should once every hour. Is there a schedule executor in Perl like in JavaScript or can I incorporate JavaScript in Perl?
This solution is with Perl.
You can use localtime() function in perl.
Calculate the difference of an Hour and shoot MySQL queries.
To understand localtime() please visit this link.
OR
You can use CPAN's Time::HiRes.
Please read about Time::HiRes here.
OR
Follow this code:
use Time::Elapse;
## somewhere in your code...
Time::Elapse->lapse(my $now);
#...rest of code execution
print "Time Elapsed: $now\n";
I suggest something like this. Include a timestamp that is carried forward to next update (adjust the meta-tag so that occurs). Some issues if sql must be run at exactly 1 hrs, but I guess it it just some maintenance. The timestamp is only updated if the sql is run, and the sql is only run if the current time is more than one hour after the previous timestamp.
The following updates the timestamp with 3600 seconds instead of using the current time. Then we are very close to running it every hour.
Some web developers don't like using meta refresh in this way, so javascript or cookie may be an option. (but if this works for you, be happy :- )
use strict;
use CGI;
#time() is number of seconds since long time ago
my $lastrun = CGI->param('lastrun') || time();
#if hour is important (ie not 58 or 61 minutes) then need to
#consider the time spent running this script, etc
if (time() > $lastrun + 60 * 60) { #one hr is 60 sec * 60 min
$lastrun += 60 * 60; #udate timestamp before starting sql
#run sql
}
#do fixed stuff every minute
print qq|
Pragma: no-cache
Content-Type: text/html
<html><head>
<!-- remember to adust the url below ---vvvvvvvvvvvvvvvv-----here -- so time is ok vvvvv -->
<meta http-equiv="refresh" content="60;URL='http://example.com/script.pl?lastrun=$lastrun">
</head>
<body>hello again, waiting...</body>
<html>
|;

Calculate amount of time until the next hour

I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions?
Thanks in advance.
To know exactly the miliseconds from now to the next hour:
function msToNextHour() {
return 3600000 - new Date().getTime() % 3600000;
}
Please note that this will strictly tell you how many milliseconds until the NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).
function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }
Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).
you have the Date object in Javascript, you could do something like:
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";
of course you will have to work more on those calculations, but that's how you work with time in javascript
Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?
Mozilla Date Docs
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:
function minsToHour() {
return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}

Categories

Resources