Analysis of Two Methods of Timing Task Execution Based on ThinkPHP Framework

  • 2021-11-01 02:28:28
  • OfStack

In this paper, two methods of executing tasks regularly in ThinkPHP framework are described by examples. Share it for your reference, as follows:

In ordinary projects, we always encounter the problem of timed execution of a certain method task. If we have the authority of the server, we can directly set timed tasks in the server, such as setting them in the task scheduler of Windows and writing scripts to execute them in Linux. If we don't have server permissions, how can we use the program code of the project to automatically execute it at regular intervals? Next, we will describe an example of executing tasks regularly based on ThinkPHP framework, and the specific methods will be described in detail below.

What needs to be reminded here about timing execution of tasks is that the method described here is passive execution, that is to say, when the system website is visited, the program will decide whether to execute the method task by comparing whether it meets the timing requirements or whether it meets the time for executing tasks, and if it does, it will be executed, otherwise it will not be executed. In addition, if the website does not have any visits and requests, it will also not be implemented. If you find out or know how to take the initiative to perform regular tasks, please leave a message and tell me, and I will also learn 1.

1. Method 1: v3.2. 1

① ThinkPHP/Library/Behavior/CronRunBehavior. class. php

The first thing to say here is this automatic task file. The official file exists in BUG. I use v version 3.2. 1. If there is any correction in the later version, you can try 1.


<?php
/**
 * =======================================
 * Created by WeiBang Technology.
 * Author: ZhiHua_W
 * Date: 2016/9/22 0005
 * Time:  Morning  11:12
 * Project: ThinkPHP Realize timed execution of tasks 
 * Power:  Automate tasks 
 * =======================================
 */
namespace Behavior;
class CronRunBehavior
{
  public function run(&$params)
  {
    if (C('CRON_CONFIG_ON')) {
      $this->checkTime();
    }
  }
  private function checkTime()
  {
    if (F('CRON_CONFIG')) {
      $crons = F('CRON_CONFIG');
    } else if (C('CRON_CONFIG')) {
      $crons = C('CRON_CONFIG');
    }
    if (!empty($crons) && is_array($crons)) {
      $update = false;
      $log = array();
      foreach ($crons as $key => $cron) {
        if (empty($cron[2]) || $_SERVER['REQUEST_TIME'] > $cron[2]) {
          G('cronStart');
          R($cron[0]);
          G('cronEnd');
          $_useTime = G('cronStart', 'cronEnd', 6);
          $cron[2] = $_SERVER['REQUEST_TIME'] + $cron[1];
          $crons[$key] = $cron;
          $log[] = 'Cron:' . $key . ' Runat ' . date('Y-m-d H:i:s') . ' Use ' . $_useTime . ' s ' . "\r\n";
          $update = true;
        }
      }
      if ($update) {
        \Think\Log::write(implode('', $log));
        F('CRON_CONFIG', $crons);
      }
    }
  }
}

This code has fixed bug, so you can copy it to the file "ThinkPHP/Library/Behavior/CronRunBehavior. class. php" for saving.

② tgs. php

Create a new tags. php file in the Application/Common/Conf folder and set the label.


<?php
return array(
    //' Configuration item '=>' Configuration value '
    'app_begin' =>array('Behavior\CronRunBehavior'),
);

③ config. php

Autorun configuration in the config. php file in the Application/Common/Conf folder.


<?php
return array(
    /*  Autorun configuration  */
    'CRON_CONFIG_ON' => true, //  Do you want to turn on autorun 
    'CRON_CONFIG' => array(
      ' Test execution timing task ' => array('Home/Index/crons', '5', ''), // Path ( Format the same R) , interval of seconds ( 0 For 1 Run directly), specifying 1 Start time 
    ),
);

④ IndexController. class. php

Timing tasks are written in Application/Home/Controller/IndexController. class. php file.


<?php
/**
 * =======================================
 * Created by WeiBang Technology.
 * Author: ZhiHua_W
 * Date: 2016/9/22 0005
 * Time:  Morning  11:20
 * Project: ThinkPHP Realize timed execution of tasks 
 * Power:  Automatic task execution method controller 
 * =======================================
 */
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller
{
  /*
  public function index(){
  $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: " Microsoft Yahei "; color: #333;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> Welcome to  <b>ThinkPHP</b> ! </p></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>','utf-8');
  }
  */
  public function index()
  {
    $contents = file_get_contents("test.txt");
    // Output the content every time you visit this path, and see the difference of the content 
    var_dump($contents);
    exit;
    $this->assign("contents", $contents);
    $this->display();
  }
  // Timing execution method 
  public function crons()
  {
    // Write content to a file 
    file_put_contents("test.txt", date("Y-m-d H:i:s") . " Perform scheduled tasks! " . "\r\n<br>", FILE_APPEND);
  }
}

In this way, we write the task regularly. Every 5 seconds, we visit the url of any project, and then look at the test. txt file in the root directory to find that the contents change.

Note: When you modify the interval time, it will not take effect. This is why you need to delete the cache file in the Runtime/Data folder, and the interval time cache is stored in the CRON_CONFIG. php file.

Click here to download the pure project file. Welcome to download and correct.

2. Method 2: v3.2. 2

This method is not much different from Method 1.

① tags. php

Create a new tags. php file in the/Application/Common/Conf directory. (1 sample in this and method 1)


<?php
return array(
    //' Configuration item '=>' Configuration value '
    'app_begin' =>array('Behavior\CronRunBehavior'),
);

② crons. php

Create a new crons. php file in the/Application/Common/Conf directory. (There is a difference between this and Method 1. Pay attention to the distinction. )


<?php
return array(
    //myplan Plan a method file for us to execute regularly ,2 Is the interval, nextruntime Next execution time 
    // This file is located in the /Application/Cron/ Directory 
    'cron' => array('myplan', 2, nextruntime),
);

③ myplan. php

Create a new Cron folder in the/Application/Common/directory, and create a new file myplan. php file.


<?php
echo date("Y-m-d H:i:s")." Perform scheduled tasks! " . "\r\n<br>";

At this point, we can access the project's url, and then we will find that the ~ crons. php file is generated in the Application/Runtime/directory, which reads as follows:


<?php
  return array (
    'cron' =>
      array (
        0 => 'myplan',
        1 => 60,
        2 => 1398160322,
      ),
  );
?>

So you can observe the results!

Readers who are interested in thinkPHP can check the topics of this site: "Introduction to ThinkPHP", "Summary of thinkPHP Template Operation Skills", "Summary of ThinkPHP Common Methods", "Introduction to codeigniter", "Advanced Course of CI (CodeIgniter) Framework", "Introduction to Zend FrameWork Framework" and "Summary of PHP Template Technology".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: