繁体   English   中英

如何在特定时间自动重新加载网页?

[英]How to automatically reload a web page at a certain time?

我有一个网站,我想在某个时间重新加载,比如下午 3:35,而不是在特定时间间隔(比如 5 分钟)之后。 我怎么做?

以下 JavaScript 片段将允许您在给定时间刷新:

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);
}

然后你可以添加一个脚本标签来调用refreshAt()函数。

refreshAt(15,35,0); //Will refresh the page at 3:35pm

请注意,此代码将根据客户端本地时间刷新。 如果您希望它在特定时间而不考虑客户端的时区,您可以将时间对象上的get*()set*()getTime()除外)替换为等效的getUTC*()setUTC*()为了将其固定到UTC。

<META HTTP-EQUIV="Refresh" CONTENT="5">

这将强制页面每 5 秒重新加载一次。 只需计算正确的间隔并将其添加到内容标签

我发现这个页面有一个类似的问题,并用它来破解一个可能对某些人有用的更具体的答案。 对于这个项目,我们希望确保在全球感兴趣的现场活动即将开始时刷新页面,激活嵌入在用户页面上的播放器(我知道用例很窄——其他人可能有更好的用途它)。

上述答案中的一个挑战是如何处理时区转换,这对我们来说是一个更大的问题,因为我们希望确保页面在特定的日期和时间刷新。 为此,我获取了目标日期和今天日期的 UTC 版本,将它们转换为 GMT,然后将 Andrew 的超时函数设置为两者之间的差异。


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);
}

基本上,当页面被访问时,计算访问时间和您想要重新加载页面的时间之间剩余的时间,并在元刷新标题中使用剩余时间。 显然,这需要在 CGI 脚本或 Web 应用程序中完成,或者可能使用 SSI(服务器端包含); 如果您只有一个静态 HTML 文件,它将无法工作。

另一种选择是使用 Javascript,但如果客户端禁用了 Javascript,它将无法工作。

这对我的目的更有效。

如果你能够使用 Jquery 和 MomentJs,你可以这样做:

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

    });
})();

基本上,有很多 JavaScript 代码可以在几分钟内刷新页面,您也可以编辑它们以在几小时内刷新。 像这个:

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

(现在只需计算您希望它刷新的分钟和秒数,例如,如果现在是中午,则每天中午:

var limit = "1440:00";

现在您可以使用此代码,但大多数代码不适用于服务器时间,并且根据您提供给我们的信息,我们真的无能为力。 编辑您的问题并告诉我们您是否希望它与服务器时间或其他时间同步。

希望对您有所帮助,您可以设置刷新的确切时间

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);
}

如果您使用 Flask,您可以将变量设置为与网络时间同步。 在 Flash 应用程序中

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

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

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

并在 html 页面中

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

在给定的分钟和秒刷新→即在固定时间的每小时可以如下:

<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>

使用它每 20 秒刷新一次页面。

<META HTTP-EQUIV="refresh" CONTENT="20">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM