Detailed PHP implementation of timed tasks to achieve the idea of _php skills

Source: Internet
Author: User
Tags curl one more line php code nginx server aliyun

PHP itself is not timed function, PHP can not be multi-threaded. PHP's timing tasks must be combined with other tools to achieve, such as WordPress built-in Wp-cron features, very powerful.

First, the Linux server using crontab timed to execute PHP

Let's start with a relatively complex server that performs PHP. PHP installed on the server, you can execute PHP files, whether or not the installation of Nginx or Apache server environment software. And Linux, using the command line, with crontab to timing tasks, is the perfect choice, but also the most efficient choice.

First, go to command line mode. Linux as a server is generally the default to enter the command-line mode, of course, we manage the server also generally through putty tools such as remote connection to the server, in order to facilitate, we use the root user login. At the command line, type:

Crontab-e

Then will open a file, and is not edit the state, then the VI editing interface, by knocking on the keyboard I, into the editing mode, you can edit the content. Each line in this file is a timed task, and we create a new line that creates a new scheduled task (which, of course, is written in a certain format in this line). Let's take an example and add one more line, which reads as follows:

* * * * * * lynx-dump https://www.yourdomain.com/script.php

What do you mean by that? In fact, the above line consists of two parts, the previous part is time, and the latter part is the operation content. Like the one above,

00 * * * *
is to perform the scheduled task when the number of minutes in the current time is 00 o'clock. The time section consists of 5 time parameters, respectively:

Time-Sharing and Lunar Week
The 1th column represents the minute 1~59 per minute or */1, and/n represents every nth minute, such as */8, which means every 8 minutes, and the following analogy
The 2nd column represents the hour 1~23 (0 for 0 points)
The 3rd column represents the date 1~31
The 4th column represents the month 1~12
The 5th list of the week 0~6 (0 for Sunday)

The latter part of the whole sentence is the specific content of the operation.

Lynx-dump https://www.yourdomain.com/script.php

This means accessing this URL through Lynx. We use the main lynx, curl, wget to achieve remote access to the URL, and if you want to improve efficiency, directly with PHP to execute local PHP files is the best choice, such as:

*/2 * * */usr/local/bin/php/home/www/script.php

This statement can be in every 2 hours of 0 minutes, through the Linux internal PHP environment to perform script.php, note that this is not through the URL access, through the server environment to execute Oh, but the direct execution, because bypassing the server environment, so the efficiency of course much higher.

Well, you've added a few scheduled tasks that you need. Click ESC on the keyboard, enter ": Wq" return, so that the set of scheduled tasks, the screen can also see the prompts to create a new scheduled task. The next step is to write your script.php well.

About Crontab more usage here does not introduce, if you want to use this timing task function more flexibly, should oneself go further study the crontab.

Second, the Windows Server using bat timed to execute PHP

There is a similar cmd and bat file on Windows and Linux, and the bat file is similar to a shell file, and executing the bat file is equivalent to sequentially executing the commands inside (and, of course, programming by logic), so We can use the Bat command file to implement PHP timed tasks on the Windows Server. In fact, timing tasks on Windows are the same as on Linux, except that the methods and approaches are different. Okay, here we go.

First, create a Cron.bat file in a location where you think it's more appropriate, and then open it in a text editor (Notepad is ok), and write something like this:

D:\php\php.exe-q D:\website\test.php
The meaning of this sentence is, use Php.exe to execute test.php this PHP file, as above Contab, bypassing the server environment, execution efficiency is also relatively high. After writing, click Save and close the editor.

The next step is to set a timed task to run Cron.bat. Turn on: "Start –> Control Panel –> Task Schedule –> Add Task Schedule", in the Open Interface set timed task time, password, by choice, put Cron.bat mount. OK, such a timed task is established, in this timing task right button, run, the timing task began to execute, at the point, will run Cron.bat processing, Cron.bat to execute PHP.

Third, non-owned server (virtual host) on the implementation of PHP timed tasks

If the stationmaster does not have own server, but rents the virtual host, cannot enter the server system to carry on the above operation. How do you do php timed tasks at this time? In fact, there are many ways.

1. Use Ignore_user_abort (true) and sleep dead loop

Directly at the beginning of a PHP document:

Ignore_user_abort (TRUE);

At this point, through the URL to access this PHP, even if the user turned off the browser (disconnected), PHP will continue to execute on the server. Using this feature, we can achieve very cow function, that is, through it to achieve the timing of the task activation, after the activation of whatever it is, in fact, a bit similar to the background task.

and sleep (n) refers to when the program executes here, temporarily do not go down, but rest n seconds. If you visit this PHP, you'll find that the page will load at least n seconds. In fact, this kind of long waiting behavior is more resource-consuming and cannot be used in a large amount of time.

So how does a timed task actually work? Use the following code to implement:

<?php

Ignore_user_abort (true);
Set_time_limit (0);
Date_default_timezone_set (' PRC '); The time to switch to China

$run _time = strtotime (' +1 Day ');//The time of the first execution of the task is at this time of tomorrow
$interval = 3600*12;

File_exists (DirName (__file__). /cron-run ')) exit (); In the directory to store a cron-run file, if the file does not exist, the description is already in the process, the task can not be activated, the second time, otherwise this file was repeatedly accessed, the server will crash out do

{
 if (!file_exists (DirName (__file__). " /cron-switch ')) break; If there is no cron-switch this file, stop execution, which is the function of a switch
 $gmt _time = Microtime (TRUE);//Current run time, accurate to 0.0001 seconds
 $loop = Isset ($ loop) && $loop? $loop: $run _time-$gmt _time; The process here is to determine how long it will take to start the task first, $loop how long it will take to execute
 $loop = $loop > 0? $loop: 0;
 if (! $loop) break; Stops sleep ($loop) If the interval of the loop is zero
 ; 
 // ...
 Execute some code
 //...
 @unlink (DirName (__file__). /cron-run '); This is done by deleting Cron-run to tell the program that the scheduled task is already in progress and cannot perform a new same task
 $loop = $interval;} while
(true);

By executing the PHP code above, you can implement timed tasks until you delete the Cron-switch file, the task will stop.

But there is a problem, that is, if the user directly access this PHP, in fact, there is no effect, the page will stop in this place, has been loading state, is there a way to eliminate this effect? Fsockopen helped us solve the problem.

Fsockopen can be implemented when requesting access to a file, do not have to get the return results to continue to execute the program, this is the usual use of curl, and we use Curl access to the Web page, we must wait for curl after loading the page, will execute the code after the curl, Although in fact curl can also achieve "non-blocking" request, but more complex than fsockopen, so we prefer fsockopen,fsockopen can be in the specified time, such as within 1 seconds, to complete the access path to make a request, After the completion of the path whether or not to return the content, its task to end here, you can continue to execute the program. With this feature, we add fsockopen to the normal program flow and make a request to the address of the scheduled task PHP that we created above to allow the timed task to execute in the background. If the URL of php above is www.yourdomain.com/script.php, then we can do this in programming:

///normal PHP execution//...
 Remote request (do not get content) function, the following can repeatedly use 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);/Open the Stream_set_timeout mode in the Manual ($FP, 1);/set Timeout $header = "Get $path http/1
  .1\r\n ";
  $header. = "Host: $host \ r \ n";
  $header. = "connection:close\r\n\r\n";//Long connection close fwrite ($fp, $header); Usleep (1000);
  This sentence is also the key, if not this delay, may be on the Nginx server can not perform successful fclose ($FP);
 Return Array (' Error_code ' => 0);

} _sock (' www.yourdomain.com/script.php ');

...//continue to perform other actions/// 

Add this code to a scheduled task submission result program, after setting the time, Commit, and then execute the above code, you can activate the timed task, and for the user submitted, there is no blocking on any page.

2, to borrow user's access behavior to perform certain delay tasks

But the above use sleep to achieve timed tasks, is a very low efficiency of a scheme. We hope not to do this in such a way that we can solve the problem of efficiency. We use user access behavior to perform tasks. User access to the site is actually a very rich behavioral resources, including search engine spiders to visit the site, can be counted as this type. When the user visits the site, add an action inside to check the task list for any tasks that have not been performed, and if so, execute the task. For users, using the above mentioned Fsockopen, do not feel that their visit unexpectedly also made such a contribution. But the disadvantage of this access is that access is very irregular, such as you want to perform a task at 2 o'clock in the morning, but this time period is very unlucky, no user or any behavior to reach your site, until 6 in the morning to have a new visit. This leads to a task that you originally intended to perform at 2 O ' 6 o'clock.

Here's a list of scheduled tasks, which means you need to have a list of all the tasks and what to do. In general, many systems use a database to record these task lists, as WordPress does. I use the file read and write features, provide hosted on the GitHub Open source project Php-cron, you can go and see. In short, if you want to manage multiple timed tasks, the single PHP above can not be properly laid out, you have to find a way to build a schedules list. Because the logic inside this is more complex, it is no longer elaborated, we only stay at the level of thinking.

3, borrow the third party timing mission Springboard

It is interesting that some service providers offer a variety of timing tasks, such as Aliyun Aces that provide a separate timing task, and you can fill out a URI under your own application. Baidu cloud BCE provides the server monitoring function, every day according to a certain time rule accesses the fixed URI under the application. There are a lot of timing tasks available on similar third-party platforms. You can use these third party timing tasks as a springboard to serve your site regularly. For example, you can set up a scheduled task on the Aliyun Ace 2 o'clock in the morning every day, and the URI executed is/cron.php. Then you create a cron.php, which uses Fsockopen to access the URL of the website where you really want to perform certain tasks, such as the www.yourdomain.com/script.phpabove, Also, multiple URLs can be accessed in cron.php. Then upload the cron.php to your ace, let the Ace timed task to visit/cron.php, and then let cron.php to remotely request the target site's timing task script.

4. Recycle include include file (to be verified)

PHP's process-oriented nature allows its program to execute from the top down, using this feature, when we use include a file, we will execute the introduced file, know the file include the program after the execution, and then down. If we create a loop, and then use sleep, and constantly include a file, so that the loop executes a certain program, you can achieve the purpose of timed execution. Instead of using while (true) to implement loops, we use the include file itself to implement loops, such as creating a do.php, which reads as follows:

if (...) exit (); To turn off execution

///... 
by a switch. Execute certain programs
//...

Sleep ($loop); This $loop is assigned to include (

dirname (__file__) before the include (' do.php '); /do.php ');

In fact, this method of execution and while is also like the idea. And also used to sleep, low efficiency.

PHP Timing task is a very interesting thing, although the truth, with the system Php.exe to directly execute PHP files more efficient, but for many ordinary webmaster, the virtual host is unable to do the direct PHP implementation of the native program. This article only provides some ideas to solve, I am only in the study, there are many problems or statements are not correct, I hope you point out; you can develop one of your own solutions through the idea of this article.

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.