php定时计划任务与fsockopen持续进程实例
Web服务器执行一个PHP脚本,有时耗时很长才能返回执行结果,后面的脚本需要等待很长一段时间才能继续执行。
如果想实现只简单触发耗时脚本的执行而不等待执行结果就直接执行下一步操作,可以通过fscokopen函数来实现。
PHP支持socket编程,fscokopen函数返回一个到远程主机连接的句柄,可以像使用fopen返回的句柄一样,对它进行 fwrite、fgets、fread等操作。
使用fsockopen连接到本地服务器,触发脚本执行,然后立即返回,不等待脚本执行完成,即可实现异步 执行PHP的效果。
例子:
复制代码 代码如下:
function triggerRequest($url, $post_data = array(), $cookie = array()){
$method = "GET"; //通过POST或者GET传递一些参数给要触发的脚本
$url_array = parse_url($url); //获取URL信息
$port = isset($url_array['port'])? $url_array['port'] : 80;
$fp = fsockopen($url_array['host'], $port, $errno, $errstr, 30);
if (!$fp) {
return FALSE;
}
$getPath = $url_array['path'] ."?". $url_array['query'];
if(!empty($post_data)){
$method = "POST";
}
$header = $method . " " . $getPath;
$header .= " HTTP/1.1\r\n";
$header .= "Host: ". $url_array['host'] . "\r\n "; //HTTP 1.1 Host域不能省略
/*以下头信息域可以省略
$header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \r\n";
$header .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5 \r\n";
$header .= "Accept-Language: en-us,en;q=0.5 ";
$header .= "Accept-Encoding: gzip,deflate\r\n";
*/
$header .= "Connection:Close\r\n";
if(!empty($cookie)){
$_cookie = strval(NULL);
foreach($cookie as $k => $v){
$_cookie .= $k."=".$v."; ";
}
$cookie_str = "Cookie: " . base64_encode($_cookie) ." \r\n"; //传递Cookie
$header .= $cookie_str;
}
if(!empty($post_data)){
$_post = strval(NULL);
foreach($post_data as $k => $v){
$_post .= $k."=".$v."&";
}
$post_str = "Content-Type: application/x-www-form-urlencoded\r\n";
$post_str .= "Content-Length: ". strlen($_post) ." \r\n"; //POST数据的长度
$post_str .= $_post."\r\n\r\n "; //传递POST数据
$header .= $post_str;
}
fwrite($fp, $header);
//echo fread($fp, 1024); //服务器返回
fclose($fp);
return true;
}
这样就可以通过fsockopen()函数来触发一个PHP脚本的执行,然后函数就会返回。 接着执行下一步操作了。
现在存在一个问题:当客户端断开连接后,也就是triggerRequest发送请求后,立即关闭了连接,那么可能会引起服务器端正在执行的脚本退出
在 PHP 内部,系统维护着连接状态,其状态有三种可能的情况:
* 0 – NORMAL(正常)
* 1 – ABORTED(异常退出)
* 2 – TIMEOUT(超时)
当 PHP 脚本正常地运行 NORMAL 状态时,连接为有效。当客户端中断连接时,ABORTED 状态的标记将会被打开。远程客户端连接的中断通常是由用户点击 STOP 按钮导致的。当连接时间超过 PHP 的时限(参阅 set_time_limit() 函数)时,TIMEOUT 状态的标记将被打开。
可以决定脚本是否需要在客户端中断连接时退出。有时候让脚本完整地运行会带来很多方便,即使没有远程浏览器接受脚本的输出。默认的情况是当远程客户端 连接 中断时脚本将会退出。该处理过程可由 php.ini 的 ignore_user_abort 或由 Apache .conf 设置中对应的"php_value ignore_user_abort"以及 ignore_user_abort() 函数来控制。如果没有告诉 PHP忽略用户的中断,脚本将会被中断,除非通过 register_shutdown_function() ,可以让我们设置一个当执行关闭时可以被调用的另一个函数.也就是说当我们的脚本执行完成或意外死掉导致PHP执行即将关闭时,我们的这个函数将会 被调用,当远程用户点击 STOP 按钮后,脚本再次尝试输出数据时,PHP 将会检测到连接已被中断,并调用关闭触发函数。
脚本也有可能被内置的脚本计时器中断。默认的超时限制为 30 秒。这个值可以通过设置 php.ini 的 max_execution_time 或 Apache .conf 设置中对应的"php_value max_execution_time"参数或者 set_time_limit() 函数来更改。当计数器超时的时候,脚本将会类似于以上连接中断的情况退出,先前被注册过的关闭触发函数也将在这时被执行。在该关闭触发函数中,可以通过调 用 connection_status() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用,该函数将返回 2。
注意,ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制,脚本将被退出,设置过的关闭触发函数也将被执行。在这时会发现函数 connection_status() 返回 3。
所以还在要触发的脚本中指明:
复制代码 代码如下:
ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort
set_time_limit(0); //取消脚本执行延时上限
或使用:
register_shutdown_function(callback fuction[, parameters]); //注册脚本退出时执行的函数

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The scheduled task is scheduled to execute atat at a specified time point at a time, and the one-time task depends on the atd service. It needs to be started to realize the at task. The at queue is stored in the /var/spool/at directory -V: Display version information -l: List the specified queue Jobs waiting to be run; equivalent to atq-d: delete the specified job; equivalent to atrm-c: view specific job tasks [root@localhost~]#systemctlstartatd[root@localhost~]#systemctlenableatd[root@localhost~]# atnow+1minat>useraddxwzat>#

Most users don’t know what the scheduled power on and off setting method for windows 7 is. Specifically, win7 can be set to automatically shut down, but users don’t know how to set it up. In fact, it can be set by entering a simple code, and you need to use cmd to set it up. The following is an introduction to the actual Windows 7 timer power on and off setting method. Users can refer to it and set it up, which is very simple. What is the method to set the timer on and off of Windows 7? 1. Set automatic shutdown. In fact, it can only be done from within the capabilities of the system itself, i.e. entering the shutdown command in the action box. Open the menu bar and click Action. If not, just press the shortcut key to open it, win+r to open it. 2. For example, if we want to turn off the power after three hours

With the rapid development of the Internet, more and more websites and applications need to perform some scheduled tasks and planned tasks in the background, such as data cleaning, backup, statistical analysis, etc. As a popular web development language, PHP also provides corresponding scheduled task and planned task technology. This article will introduce the scheduled task and planned task technology in PHP in detail. 1. Concept and usage scenarios of scheduled tasks 1.1 Concept Scheduled tasks refer to automatically executing some specified tasks or operations within a specified time point or time interval. 1.2 make

A web crawler is an automated data collection tool that can automatically capture data on the network by simulating user behavior and store or analyze it. As a widely used web development language, PHP also has a wealth of web crawler development tools and technologies. This article will introduce how to use PHP's fsockopen function to implement HTTP requests to build a simple web crawler system. The fsockopen function is a PHP related to Socket communication

Timing tasks and planned task management of PHP and small programs With the continuous development of Internet technology, many websites and applications need to perform certain tasks regularly, such as data cleaning, data analysis, data synchronization, etc. In PHP and small program development, how to manage scheduled tasks and planned tasks is an important topic. This article will introduce how to use PHP and applets to manage timed tasks and planned tasks, and give corresponding code examples. Scheduled task management in PHP In PHP, we can use Cron to manage scheduled tasks.

Laravel is a popular PHP framework that provides great support for web application development. One of the powerful and useful features is LaravelTaskScheduling. This article will introduce how to use LaravelTaskScheduling to perform scheduled tasks. 1. What is LaravelTaskScheduling scheduled task? LaravelTaskScheduling is

How to implement scheduled tasks and scheduled tasks through the Webman framework? Webman is a lightweight web framework developed based on Go language. It provides a simple way to implement scheduled tasks and planned tasks. This article will introduce how to use the Webman framework to implement timed tasks and scheduled tasks, and provide corresponding code examples. Before using the Webman framework, you need to install Webman first. Webman can be installed with the following command: gogetgithub.com/he

We often see words that start a project. In fact, this is the scheduled task setting in our computer. When our computer starts, these scheduled tasks will start with the Win7 system. Some tasks may have to be started, but others don't. In this regard, we can set up these scheduled tasks. Let's see the detailed operation. 1. First, we can find the start menu bar on the computer. In the Start menu, we can see related options, find the Control Panel option and click to enter. 2. After entering the computer's control panel, we can see the system and security options. In the first row of the current page, click the button and open it. 3. After entering the system and security options of the computer control panel, we can find the administrative tools button at the bottom.
