Home > Backend Development > PHP Tutorial > PHP定时运行

PHP定时运行

WBOY
Release: 2016-06-23 14:32:01
Original
849 people have browsed it

 

下面的这段代码,可以在当前文件夹下,生成一个test.txt,并每隔20秒,往里面写入一个时间戳,无论客户端是否关闭浏览器。
ignore_user_abort(true);
set_time_limit(0);

function write_txt(){
if(!file_exists(”test.txt”)){
$fp = fopen(”test.txt”,”wb”);
fclose($fp);
}
$str = file_get_contents(’test.txt’);
$str .= “\r\n”.date(”H:i:s”);
$fp = fopen(”test.txt”,”wb”);
fwrite($fp,$str);
fclose($fp);
}

function do_cron(){
usleep(20000000);
write_txt();
}

while(1){
do_cron();
}

关键的两个函数:

ignore_user_abort(true),这个函数的作用是,无论客户端是否关闭浏览器,下面的代码都将得到执行。

set_time_limit(0),这个函数的作用是,取消php文件的执行时间,如果没有这个函数的话,默认php的执行时间是30秒,也就是说30秒后,这个文件就say goodbay了。

另外usleep在PHP5.0之后,支持windows操作系统。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template