Home >Backend Development >PHP Tutorial >PHP scheduled tasks
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(); }
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