Home  >  Article  >  Backend Development  >  How to make PHP perform tasks regularly (with code)

How to make PHP perform tasks regularly (with code)

PHPz
PHPzforward
2016-07-29 08:33:281398browse

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>

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>

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

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete