PHP

laravel 任务调度的使用

2018-02-14  本文已影响630人  爱吃秋葵的莫冲

中文说明
上面中文说明其实已经很清楚了,把我在做的过程中的坑记录下来。

php artisan make:command SendEmails

demo:

<?php

/*
 * This file is part of PHP CS Fixer.
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Console\Commands;

use App\Repositories\FeedRepository;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'feeds 缓存';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        set_time_limit(60 * 30);

        $feed = new FeedRepository();
        $feed->cacheFeeds();
    }
}

新增成功后,执行 php artisan list 可以见到刚刚创建的command:feed:cache

<?php

/*
 * This file is part of PHP CS Fixer.
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

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 = [
        \App\Console\Commands\CacheFeeds::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     */
    protected function schedule(Schedule $schedule)
    {
        $filePath = storage_path().'/logs/cache.log';
        $schedule->command('feed:cache')
                 ->appendOutputTo($filePath)
                 ->cron('*/15 * * * *') 
                 ->after(function () {
                     echo datetime().' feed cache completed! '.PHP_EOL;
                 })
                 ;
    }

    /**
     * Register the Closure based commands for the application.
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}
* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

/path/to/artisan 就是项目地址,例如 /home/laravel-project/artisan

添加后重启crontab,service cron restart,到执行时间会在输出的log中见到。
注意点:

上一篇 下一篇

猜你喜欢

热点阅读