简体   繁体   English

我怎么能用计时器运行PHP脚本?

[英]How can i run php script with timer?

I have foreach functions that print students names 我有foreach打印学生姓名的功能

$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   sleep(3);
}

How can i print each name, each 3 seconds? 如何打印每个名称,每3秒钟? After "echo $name" i need some timer to stop the loop and wait for 3 seconds. "echo $name"我需要一些计时器来停止循环并等待3秒钟。 sleep() functions doesn't work here. sleep()函数在这里不起作用。 What else i can do? 我还能做什么?

You can not do this server side (reliably). 你不能做这个服务器端(可靠)。 This is because there is just too much possibility of your traffic being held or buffered on the way: by the webserver, by proxies along the way, by your browser, etc. It would however probably work on CLI. 这是因为在途中保持或缓冲流量的可能性太大了:通过网络服务器,沿途的代理,浏览器等等。然而,它可能适用于CLI。

So I would definitely do it client-side, without sacrificing security (if needed). 因此,我肯定会在客户端进行,而不会牺牲安全性(如果需要)。

If this is only for "cosmetic" purposes, you can create an AJAX method which will return the array of names, and then have Javascript output them with its timers. 如果这只是为了“美化”的目的,你可以创建一个AJAX方法,它将返回名称数组,然后让Javascript输出它们的计时器。

Or, you could have AJAX call the PHP script using timers, and PHP will return only one name. 或者,您可以让AJAX使用计时器调用PHP脚本,PHP将只返回一个名称。 It can save the current timestamp in the DB or in a Session variable, and don't return a new name until some time has passed. 它可以将当前时间戳保存在DB或Session变量中,并且在经过一段时间后才会返回新名称。

try using flush function 尝试使用刷新功能

ob_start();    
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   ob_flush();
   flush();    
   sleep(10);
}

You can do this with javascript, ajax 你可以用javascript,ajax来做到这一点

or with flush() function 或者使用flush()函数

<?php
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   flush();
   sleep(3);
}

working demo 工作演示

If you need to do this in a web page you need to flush the output or disable output buffering to get that work. 如果您需要在网页中执行此操作,则需要刷新输出或禁用输出缓冲以使其工作。 Some references: 一些参考:

In php CLI that code will work. 在php CLI中,代码将起作用。

You can write flush(); 你可以写flush(); after echo echo之后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM