Home PHP Framework ThinkPHP thinkphp method to set up scheduled execution tasks

thinkphp method to set up scheduled execution tasks

Apr 21, 2020 am 09:11 AM
thinkphp

thinkphp method to set up scheduled execution tasks

1. Method 1: v3.2.1

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

First of all, What we are talking about is this automatic execution task file. There is a bug in this file provided by the official. I am using version v3.2.1. You can try it if there are corrections in later versions.

<?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);
            }
        }
    }
}
Copy after login

②、tgs.php

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

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

③、config.php

Configure the config.php file in the Application/Common/Conf folder for automatic operation.

<?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为一直运行)、指定一个开始时间 
	),
);
Copy after login

④、IndexController.class.php

Write scheduled execution tasks in the Application/Home/Controller/IndexController.class.php file.

<?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);
    }
}
Copy after login

In this way, we have written the scheduled execution task. Every 5 seconds, we access the URL of any project, and then check the test.txt file in the root directory to find the changes in the content.

Note: When you modify the interval, you will find that it does not take effect. This is because you need to delete the cache file in the Runtime/Data folder. The interval cache is stored in the CRON_CONFIG.php file.

2. Method 2: v3.2.2

This method is not much different from method one.

①、tags.php

Create a new tags.php file in the /Application/Common/Conf directory. (This is the same as method 1)

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

②, crons.php

Create a new crons.php file in the /Application/Common/Conf directory. (This is different from method 1, please pay attention to the distinction.)

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

③, myplan.php

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

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

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

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

Recommended tutorial: thinkphp tutorial

The above is the detailed content of thinkphp method to set up scheduled execution tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

ThinkPHP6 backend management system development: realizing backend functions ThinkPHP6 backend management system development: realizing backend functions Aug 27, 2023 am 11:55 AM

ThinkPHP6 backend management system development: Implementing backend functions Introduction: With the continuous development of Internet technology and market demand, more and more enterprises and organizations need an efficient, safe, and flexible backend management system to manage business data and conduct operational management. This article will use the ThinkPHP6 framework to demonstrate through examples how to develop a simple but practical backend management system, including basic functions such as permission control, data addition, deletion, modification and query. Environment preparation Before starting, we need to install PHP, MySQL, Com

See all articles