2017-04-19 109 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