PHP创建定时任务 sh+php和tp5+crontab两种方式

本文介绍两种在ThinkPHP5框架中实现定时任务的方法:直接通过shell命令调用指定控制器和使用内置的命令行工具扩展。前者适用于快速部署简单的定时任务,后者提供了更完善的解决方案,包括定义专门的命令类来组织任务逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:sh(最简洁暴力):

#!/bin/bash

// 1.执行thinkphp5下到index方法
/usr/bin/php  /home/wwwroot/default/tp5/public/index.php  /index/index/index

// 2.执行thinkphp5下的test方法
/usr/bin/php  /home/wwwroot/default/tp5/public/index.php  /index/index/test

// 执行普通文件
/usr/bin/php  /root/learnScript/a.php

方式二:tp5

1.新建command文件

在application/模块/新建一个command文件夹/Test.class.php

<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;

class Test extends Command
{
    protected function configure(){
        $this->setName('Test')->setDescription("计划任务 Test");
    }

    protected function execute(Input $input, Output $output){
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/

        $this->test();

        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }

    private function test(){
        echo "test\r\n";
    }
}

2.配置command.php文件,位置在application/command.php

<?php
return ['app\admin\command\Test'];

3.运行test命令

打开命令行,运行php think Test命令test命令execute方法中运行的方法就会运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值