1103Currently online
10Today's Reading
20Share Today
Multilingual display

PHP implementation of the execution of scheduled tasks of several ideas detailed

2018-04-17 17:36:01

PHP itself does not have a timing feature. PHP's scheduled task function must be combined with other tools to achieve, such as WordPress built-in wp-cron function, very powerful. In this article, we will in-depth analysis of several common php timing task ideas.




PHP and its environment

Use CronTab on a Linux server to periodically execute php

This information is taken from experience without authorization

php is executed periodically using bat on a Windows server

windows and linux have a similar cmd and bat file, bat file is similar to a shell file, executing this bat file is equivalent to executing the commands inside (of course, you can also implement programming through logic), so, We can use the bat command file on the windows server to implement PHP timing tasks. In fact, the timing task on windows is the same as on linux, but the method and approach are different. All right, here we go. First, create a cron.bat file in a location you think is appropriate, then open it with a text editor (notepad is fine), and write something like this in it: D:\php\php.exe -q D:\website\test.php This sentence means that the use of php.exe to execute the test.php this php file, like the above contab, bypassing the server environment, the execution efficiency is relatively high. When you're done, click Save to close the editor. The next step is to set up a scheduled task to run cron.bat. Choose Start - > Control Panel - > Task Schedule - > Add Task Schedule. On the page that is displayed, set the time and password of the scheduled task, and mount the cron.bat file. Yes, so a scheduled task is established, right-click on the scheduled task, run, the scheduled task will start to execute, when the point, will run the cron.bat processing, cron.bat and then execute php.

Implement php scheduled tasks on non-owned servers (virtual hosts)

If the webmaster does not have his own server, but rents a virtual host, he cannot enter the server system for the above operations. How do you do the php timing task at this point? In fact, there are many ways. Use ignore_user_abort(true) and sleep loops to start a php document: ignore_user_abort(true); When this php is accessed through a url, php continues to execute on the server even if the user closes the browser (disconnect). Using this feature, we can achieve a very bovine function, that is, through it to achieve the activation of a scheduled task, after activation, it can do anything on its own, in fact, it is somewhat similar to the background task. And sleep(n) means that when the program is executed here, it does not go down for a while, but rests for n seconds. If you visit this php, you'll notice that the page takes at least n seconds to load. In fact, this behavior of waiting for a long time is relatively consuming and cannot be used in large quantities. So how do you implement a scheduled task? Use the following code to achieve this: 0? $loop : 0;  if(! $loop) break; // If the interval of the loop is zero, stop sleep($loop); //... // Execute some code //... @unlink(dirname(__FILE__).'/cron-run'); // This is to delete the cron-run to tell the program that the scheduled task is in the process of execution and can not execute a new same task $loop = $interval; } while(true); By executing the above php code, you can implement the scheduled task, which will not stop until you delete the cron-switch file. But there is a problem, that is, if the user accesses this php directly, there is actually no effect, the page will stop in this place, always in the loading state, is there a way to eliminate this effect? fsockopen solved this problem for us. fsockopen can implement a request to access a file, do not get the return result to continue to execute the program, which is different from the usual use of curl, we use curl to access the web page, must wait for curl to load the page, then execute the code behind curl. curl can actually make a non-blocking request, but it's much more complex than fsockopen, so we prefer fsockopen. fsockopen can complete the request to the access path within the specified time, less than 1 second, and then it doesn't matter whether the path returns the content. This is the end of its task, and it can continue to execute the program. Using this feature, we add fsockopen to the normal program flow and make a request to the address of the scheduled task php we created above, allowing the scheduled task to execute in the background. If above the PHP url is, so we in the programming, can be like this: / /... // Normal php execution program //... // Remote request (do not get content) function, the following can be used repeatedly //... // Normal php execution program //... // Remote request (do not get content) function, the following can be used repeatedly function _sock($url) {$host = parse_url($url,PHP_URL_HOST); $port = parse_url($url,PHP_URL_PORT);  $port = $port ? $port : 80;  $scheme = parse_url($url,PHP_URL_SCHEME);  $path = parse_url($url,PHP_URL_PATH);  $query = parse_url($url,PHP_URL_QUERY);  if($query) $path .= '? '.$query;  if($scheme == 'https') {    $host = 'ssl://'.$host;  }  $fp = fsockopen($host,$port,$error_code,$error_msg,1);  if(! $fp) {    return array('error_code' => $error_code,'error_msg' => $error_msg);  }  else {    stream_set_blocking($fp,true); // Enables stream_set_timeout($fp,1), the manual non-blocking mode; // Set timeout $header = 'GET $path HTTP/1.1\r\n'; $header.='Host: $host\r\n';    $header.='Connection: close\r\n\r\n'; // Close the long link fwrite($fp, $header); usleep(1000); // This sentence is also key, without this delay, fclose($fp) may not be executed successfully on the nginx server; return array('error_code' => 0);  }}_sock('www. /script.php'); //... // Continue to perform other actions //... Add this code to a scheduled task submission results program, after setting the time, submit, and then execute the above code, you can activate the scheduled task, and for the submitted user, there is no sense of congestion on the page.


Borrow the user's access behavior to perform certain delay task -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- but sleep to achieve timing task, a scheme is inefficient. We hope not to use this way of implementation, so that we can solve the efficiency problem. We borrow user access behavior to perform the task. The user's visit to the website is actually a very rich behavior, including the search engine spider's visit to the website, can be counted as this type. When the user visits the website, an action is added internally to check whether there are any tasks in the task list that have not been executed, and if so, the task is executed. For users, using the fsockopen mentioned above, they simply do not feel that their access has made such a contribution. But the downside of this kind of visit is that the visit is very irregular, you want to perform a task at 2 am, but this time period is very unlucky, no user or any action arrives on your site, and there is no new visit until 6 am. This results in tasks that you were planning to perform at 2 o 'clock not being performed until 6 o 'clock. This involves a scheduled task list, which means that you need to have a list of all the tasks when they are done and what they are done. In general, many systems use a database to keep track of these task lists, and wordpress does just that. In short, if you want to manage multiple scheduled tasks, which can't be properly organized with a single php above, you have to find a way to build a schedules list. Since the logic here is more complex, we will not elaborate in detail, we only stay at the level of ideas.


Use third party timing task springboard -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- it's fun, some service providers offer a variety of types of timing task, such as the ACE of a cloud provides a single task regularly, You can fill in a uri from your application. The cloud BCE provides the server monitoring function to access the fixed uri under the application at a certain time every day. There are also many scheduled tasks available on similar third-party platforms. You can use these third-party scheduled tasks as a springboard for your website's scheduled tasks. You can set up a scheduled task at 2 a.m. every day on some cloud ACE with the uri /cron.php executed. Then you create a cron.php that uses fsockopen to access the url of the site where you actually want to perform certain tasks, such as www above. The domain name, and you can access multiple urls in cron.php. Then upload cron.php to your ACE, have ACE's scheduled task access /cron.php, and then have cron.php remotely request the scheduled task script for the target site.


Recycled include include files (for verification) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the PHP process oriented feature makes the program from bottom to top, using this feature, When we use include a file, we execute the imported file, until the program in the include file is finished, and then execute the next step. If we create a loop, and then sleep, continue to include a file, so that the loop execution of a certain program, you can achieve the purpose of timed execution. Let's take it a step further, and instead of using while(true) to implement the loop, we'll use the included file itself to include itself, and we'll create a do.php that says something like this: if(...) exit(); // Turn off execution with a switch //... // Execute some programs //... sleep($loop); // This $loop includes ('do.php'); Previous assignment include(dirname(__FILE__).'/do.php'); In fact, the execution of this method is similar to the idea of while. And the same use of sleep, inefficient. php timing task is a very interesting thing, although to be honest, with the system of php.exe to directly execute the php file is more efficient, but for many ordinary webmaster, the virtual host is unable to do direct php execution of native programs.