laravel8 定时任务并写入日志

本文档介绍了如何在 Laravel8 中创建并执行定时任务,包括步骤:1) 创建command文件;2) 编写记录日志的任务操作;3) 在Kernel.php中调度任务;4) 使用命令行执行任务。提供了手动停止命令和一次性执行命令的差异,并建议查阅官方手册获取更多时间配置信息。

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

1、创建command文件

php artisan make:command 生成的文件名

2、进入生成的文件编写定时任务要执行的操作(这里以记录日志展示)

<?php

namespace App\Console\Commands\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class HomeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'four';        //定义名字

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('当前时间:'.date('Y-m-d H:i:s'));
    }
}

3、进入Kernel.php文件调用生成的文件

<?php

namespace App\Console;

use App\Console\Commands\Commands\HomeCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected $commands=[
        HomeCommand::class            //后面自己加入,根据你定义的文件
    ];
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('four')->everyMinute();        //定时
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

4、

通过

php artisan schedule:work

命令执行(一直执行,手动停止)

php artisan schedule:run

两个命令不同(执行一次)

更多时间配置可以去官方手册看

任务调度 | 综合话题 |《Laravel 8 中文文档 8.x》| Laravel China 社区

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值