I have a global var in my node js code. I need to reset its value to 1 everyday midnight at 12am. How is it done in node js?
I have read certain articles about node scheduler. Does it work or there are any other ways?
You can use a simple setTimeout() to schedule it yourself:
let myVar = 10;
function scheduleReset() {
// get current time
let reset = new Date();
// update the Hours, mins, secs to the 24th hour (which is when the next day starts)
reset.setHours(24, 0, 0, 0);
// calc amount of time until restart
let t = reset.getTime() - Date.now();
setTimeout(function() {
// reset variable
myVar = 1;
// schedule the next variable reset
scheduleReset();
}, t);
}
scheduleReset();
Any time your program starts, it can just call scheduleReset().
FYI, I lifted most of this code from a program I wrote (on a Raspberry Pi server) that restarts itself at 4am every night and that program has been doing that successfully for several years.
Using node-schedule this should be straightforward. Define your job with the correct cron-tab and reset the variable to the default value in the scheduleJob-callback:
const schedule = require('node-schedule');
let yourVar = 12345;
const globalResetJob = schedule.scheduleJob('0 0 * * *', () => {
yourVar = 1;
});
I need help with setting my timeout for the function. I'm trying to set the timeout for a given date and time but my conversion of them to milliseconds is not working.
Here's my code. Please help.
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
You need to parse the date using new Date().
As you said, the value of date is "2016-12-27" and the value of time is "15:30", so while concatenating them, you also need an extra space. Something like:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
Youre calling the getTime function on a string. You need to convert it into a time obj first. Be aware of the right String format. There are good resources online.
The better Way:
A timeout is killed when the browser is reloaded. Thats bad. It would be better to store the time, and regularily check if the time is reached. That would survive reloads, crashes, shutdowns etc:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
Use like this:
set("28-12-2016 12:30");
I want a box to popup at 14:00. Later i want it to disappear at 16:00. How can i do this? I am using Android Studio. I want it to be something like this:
if (Calendar.HOUR_OF_DAY > 14) {
Log.d("TIME", "Time Works!");
}
I'm unsure about Android Studio, but for JavaScript alone, you can use the setTimeout() function to invoke some task every X amount of time. Set this up to check the current time every once in a while, and if it's more than 14:00 and less than 16:00, make sure your popup is shown, otherwise close it...
setTimeout(handlePopupVisibility, 60000);
function handlePopupVisibility() {
var now = new Date();
var startTime = dateObj('2:00 PM');
var endTime = dateObj('4:00 PM');
if (now < dateEnd && now > startTime) {
// inside the range, show your element
// (assumes jQuery)
$("#popupID").show();
} else {
// outside the range, hide your element
// (assumes jQuery)
$("#popupID").hide();
}
}
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
(stolen from answer here: How to check if current time falls within a specific range considering also minutes )
Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}
I am a systems guy, so code isn't really my forte. I'm building a new front-end for our in-house ticketing system. I pull the tickets from the database as objects and iterate over them. I have it set up so that each ticket object has an "updates" property which is an array of objects describing each time it was interacted with. I use the type of interaction to determine if the timer should be effected, and if so, if it should be started or stopped.
User creates a ticket -> timer starts
Tech1 responds to the ticket asking for more information -> timer stops
User responds -> timer starts again
Tech1 escalates ticket to tech2 -> no change in timer status
Tech2 resolves issue and closes ticket -> timer stops
I've been able to get it to work with a single start/stop event (open/close, nothing in-between) per ticket, including subtracting non-business hours (nights, weekends, and holidays), but I'm having trouble coming up with a clean way to deal with multiple start/stops per ticket.
The main thing throwing a wrench in things is validating the input. For example, a user might submit a response (triggering a start event), then realize they forgot to add something and submit a second response (triggering another start event) before a tech responds.
I'd appreciate any thoughts on how to go about this or about what I can do to improve my existing code, I'm sure it is far less than optimal.
Here is an example of a ticket object:
{
"status":"closed",
"id":13137,
"importance":4,
"type":1,
"owner":"User1",
"category":"User Accounts",
"cc":[
"User2",
"User3"
],
"updates":[
{
"time":1393264332000,
"updator":"Tech1",
"event":"techClose",
"detail":"Done. Let us know if you need anything else."
},
{
"time":1393261496000,
"updator":"Tech2",
"event":"assigned",
"detail":"Tech1"
},
{
"time":1393030776000,
"updator":"User1",
"event":"clientReply",
"detail":"Actually, nevermind, just remove them from the groups."
},
{
"time":1393030632000,
"updator":"User1",
"event":"clientReply",
"detail":"Can you give me a list and I'll let ya know what to do with each?"
},
{
"time":1393002994000,
"updator":"Tech2",
"event":"techResponse",
"detail":"These accounts are disabled, they are still in the lists because the accounts still exist, but they are not able to be logged in to or accessed in any other way. It is standard practice to leave the accounts exactly as they were, but in a disabled state just in case you need to access them at a later date because any other changes cannot be reversed. If you'd prefer, we can remove them from the groups associated with those distribution lists or delete the accounts entirely."
},
{
"time":1392991707000,
"updator":"User1",
"event":"userCreate",
"detail":"Hey. Can you revise the All employee and other staff email groups to delete the people that are no longer here? Thx."
}
]
}
Here is how the above might be represented when passed into the function:
start = [1392991707000,1393030632000,1393030776000];
stop = [1393002994000,1393264332000];
And here is the function I am currently using (I'm not passing in arrays, just single ints at the moment):
function timeCalc(start, end){
// Array of non-working days (eg: weekends) in numerical weekday format starting with Sunday=0 and ending with Saturday=6
var daysOff = new Array(0,6);
// Array of non-working dates (eg: holidays) in any valid date format, such as: "October 13, 1975" or "75,10,13"
var holidays = new Array("2014,02,17","2014,05,26","2014,07,04","2014,08,01","2014,11,11","2014,11,27","2014,11,28","2014,12,25");
// Two arrays defining business hours in 24hour time. busHoursStart contains all starting times, busHoursEnd contains all ending times. So if you work 9-5 with a lunch break from 12-1, put "9,13" in start and "12,17" in end.
/*var busHoursStart = new Array("9");
var busHoursEnd = new Array("17");*/
// Just using start and end time, no array for now
var busHoursStart = 9;
var busHoursEnd = 17;
// Define other variables (no need to configure)
var datesBetween = new Array();
var oneDay = 24*60*60*1000;
var busHoursPerDay = (busHoursEnd - busHoursStart);
var subtractDays = 0;
// Create array of JS timestamps (UNIX time in milliseconds) representing each full day between the start and end dates (including the end date)
var dateDiff = Math.round(Math.abs(start.getTime() - end.getTime())/(oneDay));
for (var i=0; i<dateDiff; i++){
datesBetween.push(new Date(start.getTime()+(i*oneDay)));
}
// Remove days off
var noWeekends=$.grep(datesBetween, function(wDate){
var wFail;
$.each(daysOff,function(wKey,wVal){
if(wDate.getDay() == wVal) wFail=wDate;
});
return (wDate != wFail);
});
// Remove holidays
var noHolidays=$.grep(noWeekends, function(hDate){
var hFail;
$.each(holidays,function(hKey,hVal){
if(hDate.toDateString() == new Date(hVal).toDateString()) hFail=hDate;
});
return (hDate != hFail);
});
var days=(noHolidays.length - 1);
// This should be made into a function
// If start event is before business hours, set start time to when business hours start
if(start.getHours() < busHoursStart){
var startTime = busHoursStart;
}
// If start event is after business hours, set start time to when the next day's business hours start by adding a day to the counter
else if(start.getHours() >= busHoursEnd){
var startTime = busHoursStart;
subtractDays++;
}
else var startTime = start.getHours();
// If end is before business hours, set end time to when business hours start
if(end.getHours() < busHoursStart){
var endTime = busHoursStart;
}
// If end is after business hours, set end time to to when the next day's business hours start by adding a day to the counter
else if(end.getHours() >= busHoursEnd){
var endTime = busHoursStart;
subtractDays++;
}
else var endTime = end.getHours();
// If the end time is a later hour than the start time, add up hours from full days then add hours between start and end
if(endTime >= startTime){
var hours = (days - subtractDays) * busHoursPerDay) + (endTime - startTime);
}
// If the end time is an earlier hour than the start time, add up hours from full days then get hours between start and close time and hours between open time and end time, add them together and subtract a full day worth of time
else {
var hours = ((days - subtractDays) * busHoursPerDay) + ((busHoursEnd - startTime) + (endTime - busHoursStart));
}
console.log("Days: "+days+" Hours: "+hours);
return hours;
}