PHP服务器端定时器 [英] PHP server side timer

查看:39
本文介绍了PHP服务器端定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个带有倒计时功能的页面.我希望计时器在服务器端,这意味着当用户打开页面时,所有用户的计数器将始终处于同一时间.当计时器归零时,我需要能够运行另一个脚本,这会在重置计时器的同时执行一些操作.

I need to make a page that has a timer counting down. I want the timer to be server side, meaning that when ever a user opens the page the counter will always be at the same time for all users. When the timer hits zero I need to be able to run another script, that does some stuff along with resetting the timer.

我怎样才能用 php 做这样的事情?

How would I be able to make something like this with php?

推荐答案

从用户何时打开页面"来看,该页面不应该有自动更新机制吗?如果这不是您的意思,请查看 AJAX(如评论中所述)或更简单的 HTML META 刷新.或者,使用 PHP 和 header()

Judging from "when ever a user opens the page" there should not be an auto-update mechanism of the page? If this is not what you meant, look into AJAX (as mentioned in the comments) or more simply the HTML META refresh. Alternatively, use PHP and the header()

http://de2.php.net/manual/en/function.header.php

方法,也在这里描述:

使用 PHP 刷新页面

对于计数器本身,您需要保存结束日期(例如数据库或文件),然后将当前时间戳与保存的值进行比较.

For the counter itself, you would need to save the end date (e.g. a database or a file) and then compare the current timestamp with the saved value.

假设您的脚本文件夹中有一个包含 unix 时间戳的文件,您可以执行以下操作:

Lets assume there is a file in the folder of your script containing a unix timestamp, you could do the following:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

您可以使用http://www.unixtimestamp.com/index.php熟悉 Unix 时间戳.

You can use http://www.unixtimestamp.com/index.php to get familiar with the Unix Timestamp.

通向罗马的方式有很多种,这只是其中一种.

There are many ways that lead to rome, this is just one of the simple ones.

这篇关于PHP服务器端定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆