Tips for automatically reloading a URL at specific times using Javascript

I am having trouble getting a URL to work when invoked by a cron job.

My plan is to achieve the same outcome using Javascript: how can I refresh the page at a specific time each day (8:00 PM)?

Answer №1

If you're looking to refresh a controller from the index page, here's a script that can help accomplish that - check out this URL for more details: Hasif

Given that Javascript is limited to the front-end in your scenario, it's important to note that the user must keep the page open (as you mentioned) at all times. This means:

  • The URL will only be triggered if the user keeps their browser open (for daily tasks, relying solely on client side may not be the best approach);
  • A cron-job could be a better solution, but there's no way to prompt the browser to open at 8:00 PM daily;
  • Local time won't suffice if the URL needs to load simultaneously for all users, consider triggering it based on UTC timezone.

Resolution

  1. One option is to create a cookie that stores the last date and time when the index page was loaded by the user. Compare this with the current date each time the page loads to ensure the URL is loaded once (MDN example). You can set the cookie in the backend, or use this simple JS example:

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!' ));

  1. If the user maintains the browser open till the next day, utilize a script within the page to check the current UTC hour and update as needed:

// 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');

Answer №2

Use this handy JavaScript code snippet to schedule a page refresh:

function setRefreshTime(hours, minutes, seconds) {
var currentTime = new Date();
var refreshTime = new Date();

if(currentTime.getHours() > hours ||
   (currentTime.getHours() == hours && currentTime.getMinutes() > minutes) ||
    currentTime.getHours() == hours && currentTime.getMinutes() == minutes && currentTime.getSeconds() >= seconds) {
    refreshTime.setDate(currentTime.getDate() + 1);
}
refreshTime.setHours(hours);
refreshTime.setMinutes(minutes);
refreshTime.setSeconds(seconds);

var timeoutPeriod = (refreshTime.getTime() - currentTime.getTime());
setTimeout(function() { window.location.reload(true); }, timeoutPeriod);
 }

Simply call the setRefreshTime() function with your desired time:

setRefreshTime(15,30,0); //Page will refresh at 3:30pm

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Creating a live child component using React

My issue lies with the menu component, which is supposed to dynamically load elements in another container component. Unfortunately, the child elements are not being rendered. App.js import React, { Component } from 'react'; import './App. ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...

Using jQuery in Javascript, obtain the chosen radio option and place it within a label tag

I have a radio button for gender selection: <div class="label-inputs" name="userFieldDiv" id="genderUserFieldDiv"> <label class="required">Gender</label> <input type ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...

Monitor a user's activity and restrict the use of multiple windows or tabs using a combination of PHP and

I am looking to create a system that restricts visitors to view only one webpage at a time, allowing only one browser window or tab to be open. To achieve this, I have utilized a session variable named "is_viewing". When set to true, access to additional ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

Error Encountered in Jhipster Application During Initial Launch

Struggling with running a newly generated Jshipster 3 application using gulp serve after successful generation. My setup includes Ubuntu 16.04 and npm 3.9, but I keep encountering an error when attempting to execute gulp serve: check out this screenshot ...

Implementing Express 4: The Correct Way to Serve Routes from External Files

Something about my Express 4 application is causing me frustration. Here's the configuration: routes/profile.js var express = require('express'); var router = express.Router(); router.get('/profile', function(req, res) { res.s ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Enable jQuery Readonly for a temporary unlock

I have a form with two input fields, a checkbox for completion, and a save button. When the checkbox is ticked and the save button is clicked, the input boxes are locked from further editing. Everything is functioning correctly. I would like to add a co ...

Events triggered when a Jquery checkbox is toggled between checked and unchecked

I have written some HTML code that utilizes jQuery to manage checkboxes. <tr> <td> <div class="checkbox"> <label><input type="checkbox" id="checkbox2"></label> </div> </td> & ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Leverage a JSON variable within jQuery to showcase additional JSON variables

This code snippet is a work in progress, and there is room for improvement. The goal here is to have the content of thumb2 displayed in the #imageLoad container when a user clicks on a thumbnail inside the #placeholder DIV. Keep in mind that both Thumb and ...

Send Ajax Form using php without the use of document.ready function

I've encountered an issue with my PHP Ajax form submissions on my webpage. The code works perfectly for forms that are preloaded on the page, but I'm having trouble with dynamic forms that are called using other JavaScript functions. I'm loo ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

Animating jQuery to adjust height based on a percentage

My animation using percentage is not working as expected. It expands to the whole height instantly instead of smoothly transitioning to 100%. Here is my CSS code: #block-views{ overflow:hidden; height:20px; } This is my HTML code: <div id="block-view ...

I noticed that while my shareService is effectively sending values in Angular 2, I encounter an issue where my other components are displaying default values instead

I'm in the process of developing an application using angular 2. I have a UserService that sends a value to other components indicating whether a user is logged in or not, and it's working correctly in terms of data transmission. The issue I&apos ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...