I have a URL that is being invoked by a cron job, but I am not getting it to work.
I am planning to do the same using Javascript: how can I reload the page this way on particular hour of the day (8:00 PM)?
I wanted to reload a controller from the index page. I will write this script and place the URL in here – Hasif
Since the use of Javascript in your situation is restricted to the front-end, the user would need to keep the page open (index as you mentioned) the whole time. This means that:
the URL call will only be made if the user keeps the browser open (if this task really needs to run everyday, you should not rely on the client side to make it happen);
the cron-job you mentioned is the better alternative, but you have no way to force the user's browser to open up at 8:00 PM everyday;
the user's local time will not be useful to trigger this event if the URL is supposed to be loaded for all users at the same time, so trigger it at a certain time in the UTC timezone (for example).
Solution
Create a cookie that stores the date and time when the index page was last loaded by the user and each time the page loads, compare it to the current date and load the URL only once (MDN example). You might want to set the cookie in the backend, but a simple example to store and load it in JS:
var td =new Date(), date2store = `${td.getUTCFullYear()}-${td.getUTCMonth().toString().padStart(2,0)}-${td.getUTCDate().toString().padStart(2,0)} ${td.getUTCHours().toString().padStart(2,0)}:${td.getUTCMinutes().toString().padStart(2,0)}`;
alert('Cookie to store: last_date=' + date2store + ' --> Is it after 8 PM UTC? ' + (new Date(date2store).getUTCHours() >= 19 ? 'YES!' : 'NO!' ));
If the user keeps the browser open until the next day use a simple script loaded into the page to check the current UTC hour and update:
// place the code below in a setInterval(function() {...}, 1000*60*60);
// the if below should also the test the current cookie's datetime as the first condition
// 0 index hour exists (therefore compare with 19 instead of 20)
if(new Date().getUTCHours() >= 19) {
alert('Past 8 PM');
// save the current date and time in the cookie HERE
// reload the index page
// window.location.reload(true); // true for not using cache
// OR redirect to a new location
// window.location.href = 'https://...';
} else alert('Not 8 PM yet');
The following JavaScript snippet will allow you to refresh at a given time:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then you can add a script tag to call the refreshAt() function.
refreshAt(15,35,0); //Will refresh the page at 3:35pm
Related
I am from Germany, sorry for my English.
I am searching for a simple HTML or Javascript code to switch to another URL at a specific time.
I Run a landing Page which has an offer thats closed at April 16 at ten o clock for example. I need a little Script or code which directs to another url when the öfter will be closed.
I am thankful for any help.
Best regards
Marco
If the person has the landing page loaded and is viewing it, and you want to send them to a different URL when the offer closes, you can calculate how much time until that happens when they arrive at the landing page then send them to the new URL when that time is reached.
setTimeout will run a function after a timer has expired, and that function can change the window.location sending them to the new URL.
When the landing page loads get the current time and the time the offer expires:
let now = new Date();
let expires = new Date('2021-04-16 22:00:00');
Subtracting gives you the number of milliseconds until you reach the expires time, which is convenient because that's what the setTimeout function wants for it's "delay" parameter.
Verbosely, this could look like:
const now = new Date();
const expires = new Date('2021-04-16 22:00:00');
const delay = expires - now;
window.setTimeout(function() {
window.location = 'https://example.com/';
}, delay);
<div>
<p>This is the landing page</p>
</div>
This does not loop waiting for time to expire, as DCR warns in a comment; it just sets a timer, which the browser then takes care of.
All the math could be collapsed without using variables, so it becomes
window.setTimeout(function() {...etc...}, new Date('2021-04-16 22:00:00') - new Date());
Here is your script based on your mentioned time. After that specific time, link will be changed automatically.
"https://jsfiddle.net/rounak1/2pxLu5df/2/"
here is the code
let d1 = new Date()
var d2 = new Date('2021-04-16 22:00:00.00');
if (d1 > d2) {
window.location = 'https://www.google.com/'
}
I believe that this problem is better handled by your backend that can redirect the user to another page before the page loads since, if you do this in javascript, the page will have to load first.
However, since you want this to be implemented in Javascript you can do something like below:
var time = moment("16/04/2021 10:00", "DD/MM/YYYY HH:mm");
var now = new Date();
if (time > now) {
window.location.replace("replace with your url"); // Without allowing the user to hit the back button
}
In the above, time stores the datetime when the offer ends in the format enclosed as a string (read about this here: https://momentjs.com/docs/#/parsing/string-format/). This is compared to the time now to implement a redirect.
Read more about the redirect here: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
The above requires the usage of the moment.js library which you can find here: https://momentjs.com/
I want some javascript/jquery code to redirect my website to another domain but only within a certain period of time like redirect between 2 a.m. - 4:00 a.m. so it will be working only for two hour in the rest of the time website will work normally without redirect.
You must do something like this:
// Declare your interval, which will call the redirectFunction every seconds
var redirectInterval = setInterval(redirectFunction, 1000);
// Interval will call your function in 1 sec.
// So we call it directly here
redirectFunction();
function redirectFunction() {
var hours = new Date().getHours();
if (hours >= 2 && hours <= 4) {
// Replace by your URL
document.location.href = "https://google.com";
}
}
// Call this to cancel the redirection
// clearInterval(redirectInterval);
But the best solution would be to redirect your user to the server side.
I have a code that needs to run a count-down timer, the counter needs to count down 15 min per user even if he\she leaves the page.
this is the cookie initialize line:
document.cookie = "name=timerCookie; timeLeft=" + initialTime + "; expires=" + expires;
and this is how I update the cookie:
document.cookie = "name=timerCookie; timeLeft=" + timeLeft + "; expires=" + expires;
when I try to read the cookie I get "name=timerCookie"
am I setting the cookie correctly?
can I use cookie this way?
EDIT****:
apparently, cookie can contain only 1 segment(aka timeLeft) by removing the name value the issue was solved.
Well, I came up with this solution while I was offline and before I learned what your use case actually is.
I was thinking it would be better to use localStorage since MDN says:
"Cookies were once used for general client-side storage. While this was
legitimate when they were the only way to store data on the client, it
is recommended nowadays to prefer modern storage APIs."
Since your server needs to know about the user's "time remaining", you probably want cookies after all (unless you can just have the browser update the server at unload time), but maybe you can adapt this idea to your purpose.
I was also thinking that "even if he/she leaves the page" meant that the timer should keep ticking while they're away -- but this part should be relatively easy to fix.
I'm including this as HTML (to copy/paste) because SO snippets are sandboxed and won't run code that uses localStorage.
<!DOCTYPE html><html><head></head><body>
<p id="display">__:__</p>
<script>
let expires = localStorage.getItem("expires"); // Gets the stored expiration time
const display = document.querySelector("#display"); // Identifies our HTML element
// Makes a helper function to treat dates as accumulated seconds
const getSecondsSinceEpoch = ((date) => Math.floor(date.getTime()/1000));
// Sets the expiration time if countdown is not already running
if(!expires){
expires = getSecondsSinceEpoch(new Date()) + (60 * 15); // 15 minutes from now
localStorage.setItem("expires", expires);
}
// Calculates how long until expiration
let pageLoadedAt = getSecondsSinceEpoch(new Date());
let secondsRemaining = parseInt(expires) - pageLoadedAt;
// Starts the countdown (which repeats once per second)
setInterval(countdown, 1000);
function countdown(){
// When time expires, stops counting and clears storage for the user's next visit
if(secondsRemaining === 0){
clearInterval();
localStorage.clear(); // You don't want this here -- it resets the clock
}
else{
// Until time expires, updates the display with reduced time each second
display.textContent = formatTime(--secondsRemaining);
}
}
function formatTime(time){
let mins = Math.floor(time/60).toString();
let secs = Math.floor(time%60).toString();
secs = secs.length == 2 ? secs : "0" + secs; // Ensures two-digit seconds
return `${mins}:${secs}`
}
</script>
</body></html>
I have a Chrome extension that I am using to run some batch jobs on a site in the early hours of the morning. I already have a content script in place to run when this URL is called in Chrome and complete all the necessary jobs. I'm having a problem now figuring out the best way to string this to a scheduler so this URL gets opened automatically in a Chrome tab at 3:00 am. I am running all this code in a dedicated Azure Virtual Machine so there won't be any user logged in when the script is set to run. When the new tab has finished it's work it will close automatically, this I have already handled.
So far I have experimented with using the Windows Task Scheduler to open Chrome with the URL passed in as an argument. This method however is proving to be somewhat unreliable!
If I leave Chrome open on the Virtual Machine, is there any native Chrome API I can use to open a tab at a specific time with a URL? I've also used the following javascript function in a separate page to trigger the URL to open, however I have no mechanism to test if it's already running in another tab so this code would result in endless new tabs being opened, unless it could be adapted to check if the URL is already open, and I think this will be outside the scope of Javascript on it's own.
var myUrlToCall = "http://www.myspecialurl.com/runme.html";
//IS 3 AM YET?
function runTimer() {
setTimeout(function () {
var dtNow = new Date();
var hoursNow = dtNow.getHours() * 1;
if (hoursNow >= 3) {
//Open new window here (but how can I know if it's already open?)
window.open(myUrlToCall);
} else {
runTimer();
}
}, 3000);
}
Any thoughts on this would be much appreciated.
The chrome.alarms API is a perfect fit for your use case, to be used at an event page.
function createAlarm() {
var now = new Date();
var day = now.getDate();
if (now.getHours() >= 3) {
// 3 AM already passed
day += 1;
}
// '+' casts the date to a number, like [object Date].getTime();
var timestamp = +new Date(now.getFullYear(), now.getMonth(), day, 3, 0, 0, 0);
// YYYY MM DD HH MM SS MS
// Create
chrome.alarms.create('3AMyet', {
when: timestamp
});
}
// Listen
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name === '3AMyet') {
// Whatever you want
}
});
createAlarm();
About creating the tab: The chrome.tabs.query method can be used to check for the existence of a tab, and open a new one if necessary. I assume that you want to focus an existing tab if needed:
var url = '...';
chrome.tabs.query({
url: url
}, function(tabs) {
if (tabs.length === 0) {
chrome.tabs.create({ url:url, active: true });
} else {
// Focus first match
chrome.tabs.update(tabs[0].id, { active: true });
}
});
I am developing a website that has two back to back web broadcasts. I have used PHP to display the time that the buttons should be enabled and disabled. Now I need to use Javascript to automatically refresh the page before the first broadcast, before the second broadcast and after the second broadcast. I implemented the following script and it does refresh the page at the given time, however, it doesn't work exactly as I need it to. I need to alter the script so that it refreshes the page on Sundays at 7:45pm, 8pm and 8:30pm EST only.
I'm using a modified script from this answered question
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getUTCHours() > hours ||
(now.getUTCHours() == hours && now.getUTCMinutes() > minutes) ||
now.getUTCHours() == hours && now.getUTCMinutes() == minutes && now.getUTCSeconds() >= seconds) {
then.setUTCDate(now.getUTCDate() + 1);
}
then.setUTCHours(hours);
then.setUTCMinutes(minutes);
then.setUTCSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then I call the refreshAt() function.
refreshAt(19,45,0); //Will refresh the page at 7:45pm
refreshAt(20,00,0); //Will refresh the page at 8:00pm
refreshAt(20,30,0); //Will refresh the page at 8:30pm
Where I get confused is how to alter this script to only implement the refresh for EST on Sundays.
I figured it out. Here's the script:
function refreshAt(hours, minutes, seconds, day) {
var now = new Date();
var then = new Date();
var dayUTC = new Date();
if(dayUTC.getUTCDay() == day) {
if(now.getUTCHours() > hours ||
(now.getUTCHours() == hours && now.getUTCMinutes() > minutes) ||
now.getUTCHours() == hours && now.getUTCMinutes() == minutes && now.getUTCSeconds() >= seconds) {
then.setUTCDate(now.getUTCDate() + 1);
}
then.setUTCHours(hours);
then.setUTCMinutes(minutes);
then.setUTCSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
}
And then I just call the refreshAt() function:
refreshAt(20,00,0,1); //Will refresh the page at 8:00pm on Monday UTC or 3:00pm EST
An alternative approach would be to use Pusher. This keeps an open connection to receiving events.
Include the Pusher javascript:
<script src="http://js.pusher.com/1.11/pusher.min.js"></script>
Bind to a pusher event of "refresh" with this code:
var pusher = new Pusher('abc123'); // Get a key when you sign up and replace this
var refreshChannel = pusher.subscribe('refreshing');
refreshChannel.bind('refresh', function(thing) {
location.reload(true);
});
Then at 8pm (or whenever you want) manually issue a pusher event on the Pusher control panel page, and all of the people currently viewing the page would be reloaded.
You can add the test even for the day of the week, for example :
now.getDay() == "Sunday"
function refreshAt(day, hours, minutes, seconds)
{
Date.getDay() = day
...
}
0 is Sunday, 6 is Saturday.
I had the same problem as you. I'm building a site that sounds a lot like yours, also using PHP to enable and disable page elements before and after the broadcast time. Your solution seemed promising, but ultimately I was dissatisfied using pure Javascript for the page reload. Javascript gets its time from the client's machine, whereas PHP gets it from the server, and even a small difference between the two could wreck the whole system. (i.e. the page could refresh 30 seconds before the PHP enabled the buttons, causing some viewers to assume the whole thing is down.)
I solved the problem by using PHP to tell the Javascript function what time it is, and it works like a charm. The only issue is that it runs every day, instead of just on one day of the week, but that doesn't bother me- users will have no reason to be viewing the page other than the broadcast day.
This is all you need- I put this right after the <body> tag:
<script type="text/javascript">
setTimeout(function() { window.location.reload(true); }, 1000*<?php
$then = mktime(15,00,0);
$tomorrow = mktime(15, 00, 0, date("m") , date("d")+1);
$now = time();
if ($now > $then) {echo $tomorrow - $now;}
else {echo $then - $now;}?>); </script>