Maison  >  Article  >  cadre php  >  Méthode thinkphp pour configurer des tâches d'exécution planifiées

Méthode thinkphp pour configurer des tâches d'exécution planifiées

尚
avant
2020-04-21 09:11:176770parcourir

Méthode thinkphp pour configurer des tâches d'exécution planifiées

1. Méthode 1 : v3.2.1

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

Voici d'abord ce que je Je parle de ce fichier de tâche d'exécution automatique. Il y a un bug dans ce fichier fourni par le responsable. J'utilise la version v3.2.1. Vous pouvez l'essayer s'il y a des corrections dans les versions ultérieures.

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

②, tgs.php

Créez un nouveau fichier tags.php dans le dossier Application/Common/Conf pour définir les balises.

<?php
 
return array(
	//&#39;配置项&#39;=>&#39;配置值&#39;
	&#39;app_begin&#39; =>array(&#39;Behavior\CronRunBehavior&#39;),
);

③, config.php

Configurez le fichier config.php dans le dossier Application/Common/Conf pour un fonctionnement automatique.

<?php
return array(
	/* 自动运行配置 */ 
	&#39;CRON_CONFIG_ON&#39; => true, // 是否开启自动运行 
	&#39;CRON_CONFIG&#39; => array( 
	    &#39;测试执行定时任务&#39; => array(&#39;Home/Index/crons&#39;, &#39;5&#39;, &#39;&#39;), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间 
	),
);

④, IndexController.class.php

Écrivez les tâches d'exécution planifiées dans le fichier Application/Home/Controller/IndexController.class.php.

<?php
/**
 * =======================================
 * Created by WeiBang Technology.
 * Author: ZhiHua_W
 * Date: 2016/9/22 0005
 * Time: 上午 11:20
 * Project: ThinkPHP实现定时执行任务
 * Power: 自动执行任务方法控制器
 * =======================================
 */
namespace Home\Controller;
 
use Think\Controller;
 
class IndexController extends Controller
{
    /*
    public function index(){
    $this->show(&#39;<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; 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>欢迎使用 <b>ThinkPHP</b>!</p></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>&#39;,&#39;utf-8&#39;);
    }
    */
    public function index()
    {
        $contents = file_get_contents("test.txt");
        //每次访问此路径将内容输出,查看内容的差别
        var_dump($contents);
        exit;
        $this->assign("contents", $contents);
        $this->display();
    }
 
    //定时执行的方法
    public function crons()
    {
        //在文件中写入内容
        file_put_contents("test.txt", date("Y-m-d H:i:s") . "执行定时任务!" . "\r\n<br>", FILE_APPEND);
    }
}

De cette façon, nous avons écrit la tâche d'exécution planifiée Toutes les 5 secondes, nous accédons à l'URL de n'importe quel projet, puis vérifions le fichier test.txt dans le répertoire racine pour trouver les modifications dans le contenu. .

Remarque : lorsque vous modifiez le temps d'intervalle, vous constaterez qu'il ne prend pas effet. En effet, vous devez supprimer le fichier cache dans le dossier Runtime/Data. Le cache d'intervalle est stocké dans CRON_CONFIG. Fichier .php.

2. Méthode 2 : v3.2.2

Cette méthode n'est pas très différente de la première méthode.

①, tags.php

Créez un nouveau fichier tags.php dans le répertoire /Application/Common/Conf. (C'est la même chose que la méthode 1)

<?php
 
return array(
	//&#39;配置项&#39;=>&#39;配置值&#39;
	&#39;app_begin&#39; =>array(&#39;Behavior\CronRunBehavior&#39;),
);

②, crons.php

Créez un nouveau fichier crons.php dans le répertoire /Application/Common/Conf. (Ceci est différent de la méthode 1, veuillez faire attention à la distinction.)

<?php
 
return array(
	//myplan为我们计划定时执行的方法文件,2是间隔时间,nextruntime下次执行时间
	//此文件位于/Application/Cron/目录下
	&#39;cron&#39; => array(&#39;myplan&#39;, 2, nextruntime),
);

③, myplan.php

Créez un nouveau dossier Cron dans le répertoire /Application/Common/ et créez un nouveau fichier myplan.php dedans.

<?php
 
echo date("Y-m-d H:i:s")."执行定时任务!" . "\r\n<br>";

À ce stade, nous pouvons accéder à l'url du projet, puis nous constaterons que le fichier ~crons.php est généré dans le répertoire Application/Runtime/. Le contenu du fichier est le suivant :

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

Tutoriel recommandé : tutoriel thinkphp

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer