Home > Backend Development > PHP Tutorial > Let's talk about how to implement scheduled tasks in PHP

Let's talk about how to implement scheduled tasks in PHP

巴扎黑
Release: 2022-04-01 19:29:58
Original
1859 people have browsed it

This article will introduce you to the content of PHP scheduled tasks. I hope it will be helpful to you!

Let's talk about how to implement scheduled tasks in PHP

(1) The program only needs to be started once after setting the scheduled task, and then the program will keep running until the server is restarted

(2) If it is run repeatedly, it may not be the result you want, in which case it will start Multiple same scheduled tasks

(3) If each page includes this page, multiple permanently running programs will be started, consuming unnecessary system resources,

and also affecting the normal access of the page, if placed in front , the page will always be in the waiting state when accessed (that is an infinite loop)

<?php 
ignore_user_abort(true); //即使Client断开(如关掉浏览器),PHP脚本也可以继续执行. 
set_time_limit(0); // 执行时间为无限制,php默认的执行时间是30秒,通过set_time_limit(0)可以让程序无限制的执行下去 
$interval=60*5; // 每隔5分钟运行
$f = &#39;lock.txt&#39;;
if(file_exists($f)){ //判断标记文件是否存在,存在就退出,防止重复运行
    exit();
}
do{
    if(@get_file_contents($f) == &#39;stop&#39;){ //设置停止条件, 停止的时候只要向 lock.txt 写入 stop
        break;
    }
    @file_put_contents($f,&#39;run&#39;);//重复写入一个文件,标志已经运行计划任务
    ....省略任务代码
    sleep($interval);//程序暂停5分钟
}while(true);
@unlock($f); //删除标记文件
?>
Copy after login

This is just one way to implement it with code, and another way is to use Php cli mode to implement scheduled tasks

For example, under window Use Run->cmd

to run php.exe, then press AT and enter according to the requirements. Different systems have different methods, and Linux is different.

It has not been implemented specifically, but it is definitely possible.

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template