19

I have a website that I want to be reloaded at a certain time, like 3:35pm, not after a specific interval like 5min. How do I do that?

informatik01
  • 16,038
  • 10
  • 74
  • 104

10 Answers10

78

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

Note that this code will refresh based on the client local time. If you want it to be at a specific time regardless of the client's timezone, you can replace get*() and set*() (except getTime()) on the time objects with their getUTC*() and setUTC*() equivalent in order to pin it to UTC.

Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • could you please help with an example to have only minutes and seconds like this `refreshAt(35,0);` – davidb Jun 10 '17 at 11:42
  • Still works in 2018. I had to wrap it all i $( document ).ready(function() { but it works great. – Jason Apr 26 '18 at 21:58
  • I can confirm this helped me in 2020! **For other wanting the document ready code using jQuery:** `$(document).ready(function() { refreshAt(15,35,0); });` – Bruce Atkinson Apr 04 '20 at 22:49
  • @davidb `function refreshAtM_S(m,s) { refreshAt(0, m, s); }` –  Apr 09 '20 at 01:27
8
<META HTTP-EQUIV="Refresh" CONTENT="5">

this will force page to reload every 5 seconds. Just calculate the correct interval and add it to content tag

Sorantis
  • 14,496
  • 5
  • 31
  • 37
  • 4
    **@Sorantis:** The problem with doing it server-side is that timezones differ, and you don't always have the information on the client's tz. – Andrew Moore Aug 02 '09 at 01:46
  • 4
    Question is about specific time and not intervals of time – random Aug 02 '09 at 02:15
  • 1
    I like this solution a lot. Is not the perfect answer for the question but I think a great solution as it avoids java script. you just have to calculate the time server side. timezone should not be hard at all. – philipp Jun 27 '12 at 05:36
3

I found this page with a similar question and used it to hack out a more specific answer that may be of use to some. For this project, we wanted to make sure that the page refreshed once a live event of global interest was about to go on, activating the player embed on the user's page (narrow use case, I know -- others might have a better use for it).

One challenge in the above answers was how to deal with time zone conversions, which was more of an issue for us because we wanted to make sure that the page refreshed at a specific day and time. To do this, I grabbed a UTC version of the target date and today's date, converted them to GMT, then set Andrew's timeout function to the difference between the two.


var target = new Date("January 28, 2011 13:25:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;

var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;

refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
    setTimeout(function() { window.location.reload(true); }, refreshTime);
}
schnippy
  • 190
  • 10
  • target Date would be different in different regions, that's why we adapted your code to create directly a UTC Date at: https://gist.github.com/atfornes/346cc199c1ce6ac2a7f9bec4b65ccd83 – atfornes May 29 '20 at 16:35
  • 1
    Super helpful. I ended up using @atfornes version. I'm still baffled what "60000" in `timeOffset` is. It works, but how! – Matt Mintun Oct 26 '20 at 23:56
  • That is what I was searching for, thanks! – A. Volg May 10 '21 at 09:13
1

Basically, when the page is accessed, calculate how much time is remaining between the access time and the time you want to reload the page, and use that remaining time in the meta refresh header. Obviously this would need to be done in a CGI script or web application, or possibly with SSI (server-side includes); it won't work if all you have is a static HTML file.

Another alternative would be to use Javascript, but it won't work if the client has Javascript disabled.

David Z
  • 128,184
  • 27
  • 255
  • 279
  • 1
    **@David:** The problem with doing it server-side is that timezones differ, and you don't always have the information on the client's tz. – Andrew Moore Aug 02 '09 at 01:46
  • That may not be necessary. The OP didn't say whether he wanted to reload the page at a given time in the client's timezone or the server's timezone. – David Z Aug 02 '09 at 06:05
1

This worked better for my purposes.

If you're able to use Jquery and MomentJs, you can do this:

(function () {
    var $ = require('jquery');
    var moment = require('moment');

    function refreshPageAtTime(expiration, countdownElement) {
        var now = moment.utc();
        console.log('now', now);
        var expirationMoment = moment.utc(expiration, 'YYYY-MM-DD kk:mm:ss');
        console.log('target', expirationMoment);
        var secondsUntilRefresh = expirationMoment.diff(now, 'seconds');//http://momentjs.com/docs/#/displaying/difference/
        console.log('diff in seconds', secondsUntilRefresh);
        if (secondsUntilRefresh > 1) {
            setInterval(function () {
                secondsUntilRefresh--;
                console.log('seconds remaining', secondsUntilRefresh, 'seconds');
                if (secondsUntilRefresh <= 10) {
                    countdownElement.html(secondsUntilRefresh + '...');
                    if (secondsUntilRefresh === 0) {
                        console.warn('Refreshing now at ' + moment.utc());
                        window.location.reload(true);
                    }
                }
            }, 1000 * 1);
        }
    }

    $(document).ready(function () {
        var expiration = $('form').attr('data-expiration');
        console.log('expiration', expiration);
        $('.btn-primary:submit').after('<div id="countdownToRefresh" style="display: inline-block; color: #999; padding: 10px;"></div>');
        refreshPageAtTime(expiration, $('#countdownToRefresh'));

    });
})();
Ryan
  • 22,332
  • 31
  • 176
  • 357
0

Basically, there are many javascript codes out there that can refresh the page ever so minutes or something, you can edit them to refresh at hours too. Like this one:

//enter refresh time in "minutes:seconds" Minutes: 0 to Whatever
//Seconds should range from 0 to 59
var limit = "0:30";

if (document.images) {
    var parselimit = limit.split(":");
    parselimit = parselimit[0] * 60 + parselimit[1] * 1;
}
var beginrefresh = function () {
    if (!document.images) return if (parselimit == 1) window.location.reload()
    else {
        parselimit -= 1;
        curmin = Math.floor(parselimit / 60);
        cursec = parselimit % 60;
        if (curmin != 0) curtime = curmin + " minutes and " + cursec + " seconds left until page refresh!";
        else curtime = cursec + " seconds left until page refresh!";
        window.status = curtime;
        setTimeout("beginrefresh()", 1000);
    }
}

window.onload = beginrefresh;

(now just calculate the minutes and seconds you want it to refresh, like for example noon everyday if it were noon now:

var limit = "1440:00";

Now you could use this code except, most of them don't work with server time, And with the information you provided us, we really can't do anything more. Edit your question and tell us if you want it to be timed with the servers time, or something else.

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
Tony C
  • 568
  • 4
  • 9
  • 20
0

I hope this help,you can set the exact time for refresh

var target = new Date("November 18, 2019 10:00:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;

var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;

refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
0

if you using Flask you can set variable synchronized to network time. In the flash app

from datetime import *`
    def syncRefresh():`
      while (datetime.now().second % 10 !=0):`
          continue`
       return True`

and @app.route('/', methods =["GET"})

    def table():
       ....
         if syncRefresh():
            refreshNow = True  # refreshNow is the variable passed to the web page

and in the html page

     {% if refreshNow  %}
         <meta http-equiv="refresh"   content="1">
    {% endif %}
pmr
  • 1
0

refresh at a given minute and second → i.e. every hour at fixed time can be as follows:

<script type="text/javascript">
function refreshAt(minute, second) {
    var date= new Date();
    var hr = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    if(m ==  minute && s == second)
    {
        window.location.reload(true);
    }
    setTimeout(function() { refreshAt(minute, second); },600);
};
</script>
Michal
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 03 '22 at 01:18
-2

Use this to refresh the page every 20 seconds.

<META HTTP-EQUIV="refresh" CONTENT="20">
kleopatra
  • 51,061
  • 28
  • 99
  • 211
user2083954
  • 17
  • 1
  • 5