How to make PHP perform tasks regularly (with code)

PHPz
Release: 2018-10-23 13:53:50
forward
1440 people have browsed it

This article mainly introduces how to make PHP perform tasks regularly. It has certain reference value. Interested friends can take a look. I hope it will be helpful to you!

If you use PHP to perform certain tasks regularly, you can have the following two methods:

1. crontab under linux, scheduled tasks under windows

2. Use PHP related functions

<span style="font-size: 14px;">set_time_limit(0);<br>ignore_user_abort(true);<br>//这里写一个死循环<br></span>
Copy after login

The first method is the most common. If you don’t have permission to crontab on the PHP server, you can also find a machine of your own to regularly crontab to request the server

The second method is less reliable. Just restart Apache. Have to revisit, fastcgi would be better.

Example: Create index.php and test.txt. The function is to overwrite and write a number to test.txt every second, and the number will increase. The index.php code is as follows:

<span style="font-size: 14px;"><?php<br>ignore_user_abort(true);<br>$num=0;<br>set_time_limit(0);<br>//ini_set('max_execution_time',0);   用这句也行,效果和set_time_limit(0)一样<br>do{<br>	file_put_contents('./test.txt',$num);<br>	$num++;<br>	sleep(1);<br>}while(true);<br></span>
Copy after login

After closing the browser, I found that the script can still be executed, and the number is still increasing.

The reason is that these two key functions are at work:

ignore_user_abort(true) regardless of whether the client closes the browser, the following code will be executed.

set_time_limit(0) Cancel the execution time of the php file. If there is no this function, the default php execution time is 30 seconds, which means that after 30 seconds, this file will say goodbay.

If you do not use these two functions, you need to modify php.ini, find the max_execution_time configuration item, change 30 to 0, and set it to 0 to never expire. Just restart the server.

For more related tutorials, please visit A complete set of video tutorials on PHP programming from entry to master

Related labels:
php
source:csdn.net
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!