如何在特定时间刷新页面

how to refresh page in a specific time

我在我的 wp 页面中尝试了这段代码,但它不起作用

<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
date("d-m-Y H:i:s");
$time= date("H:i:s");
if($time == "03:40:00")
{
    echo "The new page loading in 10 seconds!";
 header("Refresh: $sec; url=$page");
}
?>

你不能在PHP中这样做,你可以为这样的任务做的是计算一个时间差并以秒为单位并设置页眉在以秒为单位的时间差异,类似于this:

<?php
$page = $_SERVER['PHP_SELF'];
$datetime1 = new DateTime('2020-05-23 18:20:10');
$datetime2 = new DateTime('2020-05-23 18:20:30');
$interval = $datetime2->diff($datetime2);
$diff = $datetime2->getTimestamp() - $datetime1->getTimestamp(); // diff in seconds
// you can just have `redirect` queryString params passed like this.
if(empty($_GET['redirect'])) {
  header("Refresh: $diff; url=$page" . "?redirect=1");
}

这里要指出的是,使用 标记而不是使用 header() 在您的页面中进行刷新,这对我来说感觉更干净,特别是如果您已经有模板引擎:

<meta http-equiv="refresh" content="20">

您可以将以下代码放入 header 并进行测试。希望对您有所帮助。

if ($time == "03:40:00") {
    echo "The new page loading in 10 seconds!";

    echo "<meta http-equiv='refresh' content='3'>";
}

注意:上面使用的元标记用于定义刷新文档本身的时间间隔。根据您的需要修改元标记的 "content" 属性中的值以刷新页面

谢谢大家,问题解决了,我用了javascript,函数auto-运行

<script>
(function myFunction() {
    var time = new Date().getHours()
    if( time == "02" ) {
    setTimeout(function(){
  window.location = 'your url';
}, 5000); 
   }
     })();
</script>

我认为这段代码更好,谢谢 Andrew Moore!

<script>
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(16,30,0); //Will refresh the page at 4:30pm
</script>