Implementation of scheduled tasks under PHP Virtual host (for reference only)

Source: Internet
Author: User
Tags flock

Because to do a simple central control in the realization of the heartbeat package, the difficulty of the normal heartbeat package is like this example I write a login sign-in script when I log on to the success of the login to the status of the success of this state to pass to the network on the central control end when I check in the completion of the script will be successful in the status of the We can clearly see where the current script is running if the script stops with the Android button, it will trigger a onscriptexit event. We just need to write the code in this event. When this event is triggered, we send the script status to close or stop for the central control side. State information in the control terminal can be clear what the script is currently in what state, but this is only idealized because sometimes the script may not be closed properly this will result in the middle of the terminal because of delays in receiving the script of the latest message the current script state can not be changed to appear to be running but actually has a script crash caused the problem , and then thought of the heartbeat packet is more open 1 thread interval One will send information to the central control side to let the central control side know that I am still running the script if it exceeds a certain period of time, the central control end will not receive the heartbeat packet of this script, then the middle side can determine that the script has been closed

to solve the problem : In fact, we have an extra action on the middle side is the interval of time to search under the database all the script records to see the latest record of each record time and the current time difference how much if there is too much difference Just let the script state corresponding to the record set close or stop to ensure that the script is closed unexpectedly this is the main problem of this article to solve


idea : Because it is a virtual host is not a real host if it is a real host then you can think of a lot of ways and do not need to be like me. For example, you can use the host system's scheduled tasks to perform certain database operations on a timed basis. You can also use some features of MySQL's super administrator to achieve timed tasks. Baidu has got some basic ideas of these ideas is to use Ignore_user_abort (); Whether the function settings and client disconnects terminate the script set_time_limit (0); To implement an infinite loop of death in this dead loop we can do certain things through sleep with the appropriate delay interval, but when I actually write the code, I find some problems that I didn't consider.

New problems arise:

1. We visit this special page to open an infinite dead loop (scheduled Task) If you open multiple then the resource consumption of the entire server is very significant impact on the site's normal access so we have to take steps to make this infinite loop (scheduled Task) can only exist 1

2 We need to have a switch to control this infinite loop to open the infinite loop (timed task) We can access the special page to open but close this infinite loop (scheduled Task) We also need 1 switches to control-----> with a TXT content to control the shutdown

3. We have access to this special page to open the Infinite Dead loop (scheduled Task) We can close this special page but this infinite loop of death is going to go on and on. We don't know what this infinite dead loop (timed task) is doing. Even if the Infinite dead loop (timed task) goes wrong, we don't know –-- > has done a simple scheduled task log to monitor the operation of this infinite loop (scheduled Task)

Web page File structure

Browse_log.php is a log file dedicated to recording the running feedback of the day's scheduled tasks

Timed_task.php is the main file you can open an infinite loop (scheduled Task) as long as you access this page

Timed_task_18-08-22.log This is actually a real log file browse_log.php is to read its contents to the Web page, but each day corresponds to a separate log file log file name will change so simply display on the page

Timed_task_config.txt is an infinite loop (timed task) profile that is primarily used to close all infinite loops (timed tasks) and to avoid opening multiple infinite loops (scheduled Tasks)


Usage:

Open Infinite Loop (timed Task): Make sure timed_task_config.txt exists and content is empty access timed_task.php wait for page feedback if the page goes into a stuck state, check the browse_log.php to see if the log has been successfully started.

Turn off infinite loops (timed tasks): Change the contents of Timed_task_config.txt to close and wait for a while to see if the log is logged off, and the shutdown is closed to success.

Log view: View browse_log.php It's important to see if the time interval for the top 2 normal logs is the same as your requirements. If there are some errors compared to the difference between a large gap then you can consider whether to open the infinite loop can all close re-open under


Code for the main file timed_task,php

<?PHPIgnore_user_abort();//function setting and client disconnection will terminate execution of the scriptSet_time_limit(0);//to set the execution time for a script to be infinitely longDate_default_timezone_set (' PRC ');//time to switch to China$interval= 20;//how often does the interval run$timed _task_config_path= "Timed_task_config.txt";//a switch responsible for stopping this infinite loop is actually a configuration file that controls the timing task mechanism if the file does not exist or if the contents are close then the timed task does not execute if open will open an infinite loop to monitor and perform the scheduled task? ><! DOCTYPE html Public"-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >PHP//question 1 How to control these infinite loops let them stop//issue 2 How to avoid opening multiple infinite loops increase the server's resource consumption//issues 3 log monitoring and avoidance of infinite loops//control with txt//php Timing Task//Detect configuration files for timed tasks Whether or not there is content//strpos ($str 1, "open")if(file_exists($timed _task_config_path)){    //There is a configuration file to start detecting content inside    $str 1=""; $str 1=Trim(file_get_contents($timed _task_config_path)); if(Is_numeric(Strpos($str 1, "Open"))) {    ////1. Open indicates that a scheduled task thread is currently running and no additional scheduled tasks are performedSend_timed_task_log ("There is already a scheduled task process exists that cannot open other processes"); Exit("There is already a scheduled task process exists that cannot open other processes"); } ElseIf(Is_numeric(Strpos($str 1, "Close"))) {    ////2. The content is close to require that the scheduled task is closed moreSend_timed_task_log ("config file requires closing all scheduled task processes"); Exit("Configuration file requires closing all scheduled task processes"); } Else {    ////3. If it is not open and close then lock the file and then modify the content inside for the open modify success        $fp=fopen($timed _task_config_path, ' w+ '); if(!is_writable($timed _task_config_path) {Send_timed_task_log ("Unable to write to configuration file, refresh Retry"); Exit("<p> cannot write to configuration file please refresh retry </p>"); }        Flock($fp,lock_ex); fwrite($fp, ' Open '); Sleep(1); Flock($fp,Lock_un); fclose($fp); //////////If the contents of the configuration file are read again to determine if the write succeeds, the subsequent infinite loop is not successfully prompted and ends the page        $str 1=""; $str 1=Trim(file_get_contents($timed _task_config_path));//echo "<p>". $str 1. "</p>";//echo "<p>". Strpos ($str 1, "open"). "</p>";//E XIT ();        if(Is_numeric(Strpos($str 1, "Open"))) {            ///////////////Modify the right to get to the scheduled task process successfullySend_timed_task_log ("Start successful Please close Web page");  Do{            $body=""; if(file_exists($timed _task_config_path)) {            $body=Trim(file_get_contents($timed _task_config_path)); if(Is_numeric(Strpos($body, "Close")) {Send_timed_task_log ("Configuration file requires all scheduled tasks to be closed"); Exit("<p> profile requires all scheduled tasks to be closed </p>"); }            } Else{Send_timed_task_log ("No scheduled task profile found"); Exit("<p> did not find the scheduled task profile process end </p>"); }                        //-----------------------The start of a timed operation-------------------------------Send_timed_task_log ("< General inspection: all normal >"); //-----------------------The end of a timed operation-------------------------------            Sleep(Rand($interval-2,$interval+2));//the function delay code executes several seconds in order to avoid some problems by avoiding exactly the same random down interval                        } while(true); }Else{Send_timed_task_log ("Failed to get permissions to the scheduled task process, refresh retry"); Exit("Failed to get permissions to the scheduled task process, refresh retry"); }    }}Else{Send_timed_task_log ("Timed task profile does not exist do not perform this"); Exit("<p> timed task profile does not exist do not perform this task </p>");}//function to send a timed task logfunctionSend_timed_task_log ($str) {        //receive log information from a script to determine the current date store this log information in a log file named after the current date .    if(Trim($str) <> ""){    $nowtimefilepath= "Timed_task_".Date("Y-m-d", Time()).". Log; $send _str=Date("Y-m-d", Time()); $send _str=Date("Y-m-d h:i:s", Time())." ----".Trim($str)." \ r \ n "; file_put_contents($nowtimefilepath,$send _str, file_append);//????? ???????}Else{            }  }?></body>

Complete :

Https://pan.baidu.com/s/1__xp1oSVdT2aDXj5BjxYHw

Implementation of scheduled tasks under PHP Virtual host (for reference only)

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.