PHP server side timer(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服务器端定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP服务器端定时器
基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
