美文网首页
Laravel任务调度配置以及遇到问题

Laravel任务调度配置以及遇到问题

作者: PHP的点滴 | 来源:发表于2019-05-15 10:11 被阅读0次

    项目经常用到定时执行的任务,比如:

    1. 数据统计
    2. 服务监控

    每次添加一条任务,就修改 crontab比较麻烦,下面介绍下,基于 Laravel的定时任务开发 注意事项

    Linux 添加一条 定时配置

    crontab -e
    * * * * * php /**项目路径**/artisan schedule:run >> /dev/null 2>&1
    (参数说明:分 时 日 月 周)
    

    开发命令行执行程序

    # 创建任务 php artisan make:command TestTask
    # 修改 TestTask 的 signature (eg: testtask {--date=}),在 handle() 中编写业务逻辑      
    # 命令号执行任务 php artisan testtask:stat
    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    
    class TestTask extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'testtask:stat';
    
        /**
         * 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()
        {
            //TODO
        }
    }
    
    

    配置定时任务

    1.修改 app/Console/Kernel.php

    class Kernel extends ConsoleKernel
    {
        protected $commands = [
            TestTask::class
        ];
        
        protected function schedule(Schedule $schedule)
        {
            //每天 凌晨 00:01 开始执行
            $cron = '01 00 * * *'; // 这里可以读取数据库中的配置
            $date = date('Y-m-d');
            $schedule->command('testtask:stat --date='.$date)->cron($cron);
    
        }
    
        /**
         * Register the commands for the application.
         *
         * @return void
         */
        protected function commands()
        {
            $this->load(__DIR__.'/Commands');
    
            require base_path('routes/console.php');
        }
    }
    
    1. php.ini 中 开启函数 proc_open、proc_get_status

    遇到问题 & 注意事项

    * 配置按照流程配置完毕,指定了执行的时间后,执行 php /项目路径/artisan schedule:run
    * 总是提示  No scheduled commands are ready to run。
    * 解决: 1.检查 laravel 项目的时区 2.检查 linux 系统的时区
    

    我的博客地址:
    http://itman.su520.com/2019/05/15/laravel%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E9%85%8D%E7%BD%AE%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9/

    相关文章

      网友评论

          本文标题:Laravel任务调度配置以及遇到问题

          本文链接:https://www.haomeiwen.com/subject/dwvuaqtx.html