简体   繁体   中英

Laravel Command Schedule Not Working Properly

I'm building a project with Laravel 7.28 on localhost. I need to update a PDF every hour. For the beginning I created a command:

<?php

namespace App\Console\Commands;

use App\Event;
use Illuminate\Console\Command;

class PDF extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pdf:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'All Country PDFs updated';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $event = new Event();
        $event->user_id = 1;
        $event->save();

        echo 'done';
    }
}

It just insert a record into events table and works fine. Then I edited the Kernel.php under App\\Console directory.

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\PDF::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('pdf:update')->everyMinute();
    }

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

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

Finally, I run php artisan schedule:run . I was expecting that the command runs every minute but it just runs once. is this a problem on localhost or did I do something wrong?

The php artisan schedule:run just runs once by its definition:

The schedule:run Artisan command will evaluate all of your scheduled tasks and determine if they need to run based on the server's current time.

If you want to do it every minute you should use a scheduled process control system like supervisor or crontab or etc. ( more info here )

In case if you are using laravel 8.x and running on a development/local server you can use the following command and it will work for you:

php artisan schedule:work

对于 Laravel 7,您还可以使用以下命令在本地运行

while true; do php artisan schedule:run; sleep 60; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM