美文网首页
Laravel 自定义命令及任务调度

Laravel 自定义命令及任务调度

作者: phpnet | 来源:发表于2019-12-12 12:00 被阅读0次

    自定义命令

    <?php
    namespace App\Console\Commands;
    
    use Illuminate\Support\Facades\Redis;
    use App\Services\SpreadsheetService;
    use Illuminate\Console\Command;
    
    class CreateTask extends Command
    {
    
        private $spreadsheet;
    
        private $limit = 200000;
    
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'create:task {key?} {filename?} {worksheet?}';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Create a scrapy queue task';
    
        /**
         * Create a new command instance.
         *
         * @return void
         */
        public function __construct()
        {
            parent::__construct();
            $this->spreadsheet = new SpreadsheetService($this->limit);
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $key = $this->argument('key') ?: 'queue:task';
            $worksheet = $this->argument('worksheet') ?: '';
            $filename = storage_path($this->argument('filename') ?: 'task.xlsx');
            if (! file_exists($filename)) {
                return $this->error('file not found: ' . $filename);
            }
    
            $total = 0;
            $array = [];
            $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            switch ($extension) {
                case 'xlsx':
                case 'xls':
                    $data = $this->spreadsheet->reader($filename, $worksheet, false);
                    foreach ($data as $list) {
                    }
                    break;
                default:
                    return $this->error('格式不支持');
            }
            return $this->info('finish!');
        }
    }
    
    

    任务调度

    添加调度器

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

    这个 Cron 会每分钟执行一次 Laravel 的命令行调度器。当 schedule:run 命令被执行的时候,Laravel 会根据你的调度执行预定的程序。

    定义调度

    // schedule
    $schedule->call(function () {
        DB::table('recent_users')->delete();
    })->daily();
    
    // 除了使用闭包来定义任务调度外,你也可以使用 invokable objects。
    // Invokable objects 指的是 PHP 中含有 __invoke 方法的类。
    $schedule->call(new DeleteRecentUsers)->daily();
    
    // Artisan 命令调度(推荐)
    $schedule->command('emails:send Taylor --force')->daily();
    
    // 队列任务调度
    $schedule->job(new Heartbeat)->everyFiveMinutes();
    
    // Shell 调度
    $schedule->exec('node /home/forge/script.js')->daily();
    

    调度频率设置

    方法 描述
    ->cron('* * * * *'); 自定义 Cron 计划执行任务
    ->everyMinute(); 每分钟执行一次任务
    ->everyFiveMinutes(); 每五分钟执行一次任务
    ->everyTenMinutes(); 每十分钟执行一次任务
    ->everyFifteenMinutes(); 每十五分钟执行一次任务
    ->everyThirtyMinutes(); 每三十分钟执行一次任务
    ->hourly(); 每小时执行一次任务
    ->hourlyAt(17); 每小时第 17 分钟执行一次任务
    ->daily(); 每天午夜执行一次任务(译者注:每天零点)
    ->dailyAt('13:00'); 每天 13 点执行一次任务
    ->twiceDaily(1, 13); 每天 1 点及 13 点各执行一次任务
    ->weekly(); 每周执行一次任务
    ->weeklyOn(1, '8:00'); 每周一的 8 点执行一次任务
    ->monthly(); 每月执行一次任务
    ->monthlyOn(4, '15:00'); 每月 4 号的 15 点 执行一次任务
    ->quarterly(); 每季度执行一次任务
    ->yearly(); 每年执行一次任务
    ->timezone('America/New_York'); 设置时区

    小技巧

    1. 避免任务重复
    $schedule->command('emails:send')->withoutOverlapping();
    
    1. 任务只运行在一台服务器上
    // 你的应用默认缓存驱动必须是 memcached 或 redis 才能使用这个特性。除此之外,所有服务器必须使用同一台中央缓存服务器来通信。
    $schedule->command('report:generate')->fridays()->at('17:00')->onOneServer();
    
    1. 后台任务
    // 针对有长时间运行的命令
    $schedule->command('analytics:report')->daily()->runInBackground();
    

    相关文章

      网友评论

          本文标题:Laravel 自定义命令及任务调度

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