[PHP]如何在laravel中写一个cronjob任务

    技术2022-07-11  84

    参考: https://tutsforweb.com/how-to-set-up-task-scheduling-cron-job-in-laravel/

    中文资料有很多,但是发现都不太可行,最后参考上文完成

    一. 创建文件:WordOfTheDay.php, in the app/Console/Commands directory.

    <?php namespace App\Console\Commands; use Illuminate\Console\Command; class WordOfTheDay extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; /** * 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 mixed */ public function handle() { // } }

    在handle里面写job逻辑

     

    二. Registering the Command

    Go to app/Console/Kernel.php file that looks like this,并添加

    <?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\WordOfTheDay::class, ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('word:day') ->daily(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }

    三. Task Scheduler in Laravel

    protected function schedule(Schedule $schedule) { $schedule->command('word:day') ->daily(); }

    四. Starting the Laravel Scheduler

    cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

    输入上述命令,如果是docker,就进入docker的控制台输入:lando ssh -s [项目]

    Processed: 0.013, SQL: 9