Skip to content

定时任务

youlai-think 当前未集成定时任务框架。如有需求,推荐以下方案:

推荐方案

方案一:think-queue

ThinkPHP 官方队列扩展:

bash
composer require topthink/think-queue

配置

php
// config/queue.php
return [
    'default' => 'redis',
    'connections' => [
        'redis' => [
            'type' => 'redis',
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'port' => env('REDIS_PORT', 6379),
            'password' => env('REDIS_PASSWORD', ''),
            'select' => env('REDIS_DB', 0),
        ],
    ],
];

创建任务

php
<?php
namespace app\job;

use think\queue\Job;

class SendEmail
{
    public function fire(Job $job, $data)
    {
        // 处理任务
        $this->sendEmail($data);
        
        // 标记任务完成
        $job->delete();
    }

    protected function sendEmail($data)
    {
        // 发送邮件逻辑
    }
}

推送任务

php
use think\facade\Queue;

Queue::push('app\job\SendEmail', ['to' => 'user@example.com']);

方案二:系统 Cron

创建命令行脚本:

php
<?php
namespace app\command;

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

class CleanupCommand extends Command
{
    protected function configure()
    {
        $this->setName('cleanup')
            ->setDescription('清理过期数据');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始清理...');
        // 清理逻辑
        $output->writeln('清理完成');
    }
}

注册命令

php
// config/console.php
return [
    'commands' => [
        'cleanup' => 'app\command\CleanupCommand',
    ],
];

Cron 配置

bash
# 每天凌晨 2 点执行
0 2 * * * cd /path/to/project && php think cleanup

方案三:Laravel Schedule 风格

使用第三方扩展:

bash
composer require godruoyi/php-snowflake

常用场景

场景频率说明
数据清理每天凌晨清理过期数据
报表生成每天凌晨生成统计报表
消息推送实时异步消息通知

相关资源

基于 MIT 许可发布