如何在PHP中使用setInterval? [英] How To Use setInterval in PHP?

查看:312
本文介绍了如何在PHP中使用setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问的是,一段时间后,如何像在Javascript中使用setInterval一样,一次又一次地自动使用php函数.我们设置时间,直到脚本中止或关闭为止,它一直在执行.

I want to ask that how can i use php function again and again after some time automatically just like setInterval in Javascript. We set the time and it is on its job until the script is aborted or closed.

INDEX.PHP

<?
$Wall = new Wall_Updates();
$updatesarray=$Wall->Updates();
foreach($updatesarray as $data)
{
    $likes=$data['likes'];
    ?>
    <div id="likes"><?php echo $likes; ?></div>
    <?
}
?>

和Wall_Updates()函数在 FUNCTION.PHP

And Wall_Updates() Function is defined here in FUNCTION.PHP

<?php

class Wall_Updates {    
    public function Updates() {
        $myname=$_COOKIE['usename'];
        $query=mysql_query("SELECT * FROM posts WHERE name='$myname'");
        while($row=mysql_fetch_array($query))
            $data[]=$row;
        return $data;
    }
}
?>

我希望此Wall_Updates()函数一次又一次从mysql获取数据.因此,它将被更新.

I want this Wall_Updates() function to fetch data from mysql again and again.So, It will be Updated.

推荐答案

记录如下:我认为这是个坏主意.但是:)

For the record: I think it's bad idea. But whatever :)

尝试此代码

function setInterval($f, $milliseconds)
{
    $seconds=(int)$milliseconds/1000;
    while(true)
    {
        $f();
        sleep($seconds);
    }
}

用法:

setInterval(function(){
    echo "hi!\n";
}, 1000);

或者:

$a=1; 
$b=2;

setInterval(function() use($a, $b) {
    echo 'a='.$a.'; $b='.$b."\n";
}, 1000);

这篇关于如何在PHP中使用setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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