2017-04-19 104 views
2

我有一个问题,我一直在想最近。PHP时间和差异

我想弄清楚如何创建一个2分钟的倒数计时器,即使没有客户端运行PHP脚本,也会持续运行。 (如果连接到该页面的客户端表示它会提供22秒左右的时间,并且在此之后它将重置为2分钟)。

我正在考虑创建一个时间戳来记录时间()以及计算实际时间和重新格式化的目标时间之间的差异。但是,由于我提出了另一个问题,php脚本如何知道什么时候每2分钟重置一次?

我不知道如何解决这个问题,也许它没有解决方案,但我很乐意看到一些可以帮助我的想法!

谢谢!

<?php 

/* A countdown timer of 2 minutes would be set from a specific time in anytime time I'd set ($timestamp), it should be able to reset everytime it reaches 0 or negative, it'd be synchronized to all users connected (everyone would see the same)*/ 
    function generate_newtimestamp() 
    { 

    } 
    $timestamp = mktime(21, 43, 0, 4, 19, 2017); //(hour,minute,second,month,day,year) say this variable would start off 2 minutes ahead of current time at any time that was set, and this variable needs to self_update once 2 minutes pass (maybe server-sided...Any ideas?) 
    $today = time(); 

// now I want to calculate the difference between the actual time itself and the 2 minutes target time I want it to run 
if(!negativeTimestamp($timestamp, $today)) 
{ 
    $difference =($timestamp-$today); 
    $minutes = floor($difference/60); 
    $sec = ($difference/60 - $minutes) * 60; 
    echo $minutes . "<br>"; 
    echo $sec; 
}else{ 
    generate_newtimestamp(); 
} 

function negativeTimestamp($time, $stamp) 
{ 
    $difference =($stamp-$time); 
    return ($stamp-$time<$difference) ? true : false; 
} 
?> 
+0

你有什么试过,请给我们看一些代码? – Script47

+1

存储客户端将该页面加载到“会话”中的时间。在下次加载时比较时间。 – chris85

+0

在[所以]你应该尝试**自己编写代码**。后** [做更多的研究](//meta.stackoverflow.com/questions/261592)**如果你有问题,你可以**发布你已经尝试**与清楚的解释是什么是'工作**并提供[** Minimal,Complete和Verifiable示例**](// stackoverflow.com/help/mcve)。我建议阅读[问]一个好问题和[完美问题](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要参加[游览]并阅读[this](// meta.stackoverflow.com/questions/347937/)**。 –

回答

1

我会简单地执行当前时间一些计算四舍五入它为最接近的2个全分钟。从那里,我将解决这个四舍五入时间和当前服务器时间之间的差异。事情是这样的:

$now = time(); 
$nextTwoMinute = ceil($now/120) * 120; //120 seconds = 2 minutes 
print_r("Time Left: " . ($nextTwoMinute - $now)); 

这意味着你的应用程序将不再需要在后台运行,当用户请求页面它可以依靠从服务器的时间信息。显然,如果你需要每两分钟运行一个函数,它需要cron函数的更多内容。

+0

实际工作xD!感谢您的知识! – Hxfs

0

在某处存储时间戳并创建cron job每隔几秒运行一次。如果current_time - timestamp> = 120秒:继续,否则: 中止。

(它不会是非常精确的,但将工作)

+0

我很感谢您的评论,但是这对我来说是不可能的,因为我无法运行cron作业:[ – Hxfs

+0

您是否考虑过使用Web Cron服务? –

+0

对不起延迟回复,请介意详细解释这是什么? – Hxfs