PHP scheduled tasks

巴扎黑
Release: 2016-11-23 11:23:41
Original
1030 people have browsed it

PHP is a weakly typed interpreted language. Its implementation determines that it does not have the concept of AppServer such as Java and .Net. The http protocol is a stateless protocol. PHP can only be triggered by the user and will automatically exit the memory after the call. ,Without resident memory, there is no way to ,accurate timing processing.


If you need to use PHP to execute certain tasks regularly, you can have the following methods:
1. Crontab under Linux, scheduled tasks under windows
2. set_time_limit(0);
ignore_user_abort(true);
Infinite loop

The first type: PHP files that are executed regularly by crontab. Generally, a table is needed to record the name of each task, current process ID, update time, process start ID and other information. The batch processing process includes: pre-execution preparation, execution, and post-execution processing. The entire processing process can use OO ideas to encapsulate a batch processing base class. Each batch processing task can inherit this base class to implement data processing.

The second type: triggering execution by accessing this file, there is a problem of terminating after the Apache server is restarted or the machine is restarted (windows environment). An example is as follows:

ignore_user_abort(true);  // 设置关闭浏览器后也可执行
set_time_limit(0);  // 设置相应时间无限制,原默认30s
function write_txt()
{
$filename = 'test.txt';
if (!file_exists($filename))
{
$fp = fopen($filename, 'w');
fclose($fp);
}
$fp = fopen($filename, 'r+');
$str = file_get_contents($filename);
$str .= date('Y-m-d H:i:s')."\r\n";
fwrite($fp, $str);
fclose($fp);
}
function do_cron()
{
write_txt();
sleep(30);
}
while (1)
{
do_cron();
}
Copy after login

connection_aborted() — Check if the client has been disconnected and return 1, otherwise return 0
connection_status — Return the status bit of the connection 0 - NORMAL (normal); 1 - ABORTED (abnormal exit); 2 - TIMEOUT

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!