当前位置:网站首页>Detailed explanation of several ideas for implementing timed tasks in PHP

Detailed explanation of several ideas for implementing timed tasks in PHP

2022-07-07 16:21:00 Full stack programmer webmaster

Linux On the server CronTab Timing execution php

Let's start with a relatively complex server php Talking about . There is... Installed on the server php, You can execute php file , Whether installed or not nginx or Apache Such server environment software . and Linux in , Using the command line , use CronTab To schedule tasks , It's also a great choice , And it is also the most efficient choice .

First , Enter command line mode . As a server linux In general, it enters the command line mode by default , Of course , We manage servers through putty And other tools to connect to the server remotely , For convenience , We use it root The user login . Type on the command line :

crontab -e

And then you open a file , And it's non editing , It is vi The editing interface of , By tapping on the keyboard i, Enter edit mode , You can edit the content . Each line in this file is a timed task , Let's create a new line , Is to create a new scheduled task ( Of course, it means to write in a certain format in this line ). Let's take an example , Add a row , The contents are as follows :

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

What does that mean ? In fact, the line above is made up of two parts , The first part is time , The latter part is the operation content . For example, this one above ,

00 * * * *

It means when the number of minutes in the current time is 00 when , Perform the timing task . The time part is made up of 5 It is composed of two time parameters , Namely :

 branch   when   Japan   month   Zhou 

The first 1 List minutes 1~59 Every minute or */1 Express ,/n each n minute , for example */8 It's every 8 Minute means , And so on The first 2 List hours 1~23(0 Express 0 spot ) The first 3 List date 1~31 The first 4 List month 1~12 The first 5 Column ID week 0~6(0 Sunday )

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

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

That means through lynx Visit this url. We mainly use lynx、curl、wget To achieve the right url Remote access to , And if you want to be more efficient , Direct use php To perform local php Files are the best choice , for example :

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

This statement can be used in every 2 Hours of 0 minute , adopt linux Inside php Environmental execution script.php, Be careful , This is not through url visit , Execute through the server environment , I'm going to do it directly , Because it bypasses the server environment , So of course, the efficiency is much higher .

Okay , I've added several required timing tasks . Click on the Esc key , Input “:wq” enter , This saves the set timing task , You can also see a prompt on the screen to create a new scheduled task . The next step is to write your script.php 了 .

About CronTab I won't introduce more usage of , If you want to use this timed task function more flexibly , You should study further by yourself crontab.

Windows On the server bat Timing execution php

windows Shanghe linux There's a similar one on the table cmd and bat file ,bat The document is similar to shell file , Execute this bat file , It's like executing the commands in turn ( Of course , It can also be programmed by logic ), therefore , We can use bat The command file is in windows The server implements PHP Timing task . In fact, windows Last scheduled task , and linux The truth is the same , It's just different ways and means . All right, here we go .

First , Create a place where you think it's appropriate cron.bat file , Then open it with a text editor ( Notepad is OK ), Write something like this in it :

D:\php\php.exe -q D:\website\test.php

The meaning of this sentence is , Use php.exe To carry out test.php This php file , And the above contab equally , Bypassing the server environment , The implementation efficiency is also relatively high . After writing , Click save , Close the editor .

The next step is to set up a scheduled task to run cron.bat. In turn, open :“ Start –> Control panel –> Task plan –> Add task plan ”, Set the time of the scheduled task in the open interface 、 password , By choice , hold cron.bat Mount it in . determine , Such a scheduled task is established , Right click on this timing task , function , The timing task started , When it's time , It will run cron.bat Handle ,cron.bat To perform php.

Non owned servers ( Virtual host ) Implemented on php Timing task

If the webmaster doesn't have his own server , Instead, rent a virtual host , You cannot enter the server system to perform the above operations . How to proceed at this time php What about scheduled tasks ? In fact, there are many methods .

Use ignore_user_abort(true) and sleep Dead cycle

In a php At the beginning of the document, just say :

ignore_user_abort(true);

At this time , adopt url Visit this php When , Even if the user turns off the browser ( disconnect ),php It will also continue to execute on the server . Take advantage of this feature , We can achieve great functions , That is to realize the activation of scheduled tasks through it , After activation, whatever it does , In fact, it is a little similar to background tasks .

and sleep(n) When the program is executed here , Don't proceed for the time being , But rest n Second . If you visit this php, You will find that the page at least needs to be loaded n Second . actually , This behavior of waiting for a long time consumes resources , Don't use a lot of .

So how to realize the scheduled task ? Use the following code to achieve :

<?php
ignore_user_abort(true);
set_time_limit(0);
date_default_timezone_set('PRC'); //  Time to switch to China 
$run_time = strtotime('+1 day'); //  The first execution time of the scheduled task is this time tomorrow 
$interval = 3600*12; //  Every time 12 Once an hour 
if(!file_exists(dirname(__FILE__).'/cron-run')) exit(); //  Store one in the directory cron-run file , If this file does not exist , Description is already in the process of implementation , This task can no longer be activated , Carry out the second , Otherwise, this file will be accessed many times , The server is about to crash 
do {
  if(!file_exists(dirname(__FILE__).'/cron-switch')) break; //  If it doesn't exist cron-switch This file , Stop execution , This is the function of a switch 
  $gmt_time = microtime(true); //  Current running time , Accurate to 0.0001 second 
  $loop = isset($loop) && $loop ? $loop : $run_time - $gmt_time; //  The purpose of processing here is to determine how long it will take to start the first task ,$loop It is the time interval of how long to wait for execution 
  $loop = $loop > 0 ? $loop : 0;
  if(!$loop) break; //  If the interval of the cycle is zero , Then stop 
  sleep($loop); 
  // ...
  //  Execute some code 
  // ...
  @unlink(dirname(__FILE__).'/cron-run'); //  Here is by deleting cron-run To tell the program , This scheduled task is already in the process of execution , You can't perform a new and the same task 
  $loop = $interval;
} while(true);

By executing the above paragraph php Code , You can achieve scheduled tasks , Until you delete cron-switch file , This task will stop .

But there's a problem , That is, if the user directly accesses this php, It doesn't actually work , The page will also stop here , It's always loaded , Is there a way to eliminate this effect ?fsockopen Helped us solve the problem .

fsockopen When requesting access to a file , You don't have to get the return result to continue to execute the program , This is the curl Where the usual usage is different , We are using curl When visiting a web page , Be sure to wait curl After loading the web page , Will execute curl Later code , Although in fact curl It can also be realized “ Non-blocking type ” Request , But compared to fsockopen It's a lot more complicated , So we prefer fsockopen,fsockopen Within the specified time , such as 1 Within seconds , Complete the request for access path , After completion, whether this path returns content or not , Its task ends here , You can continue to execute the program . Take advantage of this feature , We add fsockopen, For the scheduled task we created above php Send a request to the address of , The scheduled task can be executed in the background . If this up here php Of url The address is www.yourdomain.com/script.php, So we're programming , It can be like this :

// ...
//  natural php Execution procedure 
// ..
//  The remote request ( Don't 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);// It turns on the non blocking mode mentioned in the manual 
    stream_set_timeout($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 closed 
    fwrite($fp, $header);
    usleep(1000); //  This sentence is also the key , Without this delay , May be in nginx It cannot be executed successfully on the server 
    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 , Submit , Then execute the above code , You can activate the scheduled task , And for the submitted user , There is no blockage on any page .

Borrow the user's access behavior to perform some delayed tasks

But it uses sleep To achieve timing tasks , It is a very inefficient scheme . We hope not to use this method to execute , In this way, the problem of efficiency can be solved . We use user access behavior to perform tasks . Users' access to the website is actually a very rich behavioral resource , Including the visit of search engine spiders to the website , Can be counted as this type . When users visit the website , Add an action inside , Check whether there are tasks not executed in the task list , If there is , Just carry out this task . For users , Use the above fsockopen, I don't feel that my visit has made such a contribution . But the disadvantage of this kind of access is that the access is very irregular , For example, you hope that in the early morning 2 Click to perform a task , But this time period is very unlucky , No user or any behavior arrives at your website , Until morning 6 There is a new visit at . This leads to your original intention 2 Point to perform the task , To 6 It was executed at .

Here is a scheduled task list , In other words, you need to have a list to record the time of all tasks 、 What to do . Generally speaking , Many systems use databases to record these task lists , such as wordpress That's what it does . I use the file read-write feature , Provides hosting in github The open source project on php-cron, You can go and have a look at . All in all , If you want to manage multiple scheduled tasks , Single on top php It cannot be reasonably arranged , We must find a way to build a schedules list . Because the logic is more complex , I won't go into details , We just stay at the level of thinking .

Use the third-party timed task springboard

What's interesting is , Some service providers provide various types of scheduled tasks , For example, Alibaba cloud's ACE Separate scheduled tasks are provided , You can fill in one of your applications uri. Baidu cloud BCE Provides server monitoring function , Every day, I will visit the fixed under the application according to a certain time rule uri. There are many scheduled tasks available on similar third-party platforms . You can use these third-party timed tasks as a springboard , Serve your website with scheduled tasks . for instance , You can use Alibaba cloud ACE Set up an early morning every day 2 Timed task of dot , Executive uri yes /cron.php. Then you create a cron.php, The inside uses fsockopen Visit the website where you really want to perform certain tasks url, For example, above www.yourdomain.com/script.php, And in cron.php You can also access multiple url. And then put cron.php Upload to your ACE The above to , Give Way ACE Scheduled tasks to visit /cron.php, And then let cron.php Go to remote request the scheduled task script of the target website .

Recycle include Include files ( To be verified )

php The process oriented feature makes its program execute from top to bottom , Take advantage of this feature , When we use include A file , The imported file will be executed , know include After the program in the file is executed , I'm going to keep going . If we create a loop , recycling sleep, constantly include Some document , Make the loop execute a certain program , It can achieve the purpose of regular execution . Let's go one step further , Not use while(true) To achieve the cycle , Instead, use the quilt include The document itself include By itself , Let's create a do.php, Its contents are as follows :

if(...) exit(); //  Turn off the execution through a switch 
// ... 
//  Perform certain procedures 
// ...
sleep($loop); //  This $loop stay include('do.php'); Previous assignment 
include(dirname(__FILE__).'/do.php');

In fact, through this method, and while The train of thought is also like . And also used sleep, Low efficiency .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/113196.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071406056976.html