zoukankan      html  css  js  c++  java
  • Laravel 的计划任务

    避免并发执行

    $schedule->command('emails:send')->withoutOverlapping();
    

    这里需要注意,对于 call function 定义的计划任务,需要定义 name。否则会报错

    production.ERROR: A scheduled event name is required to prevent overlapping. Use the 'name' method before 'withoutOverlapping'.

    正确的做法是

    $schedule->call(function () {
                DB::table('recent_users')->delete();
    })->daily()
      ->name('project_delete_users')
      ->withoutOverlapping();
    

    编辑任务

    app/Console/Kernel.php

    protected function schedule(Schedule $schedule)
    {
            $schedule->call(function () {
                DB::table('recent_users')->delete();
            })->daily();
    }
    

    注意这里使用了匿名函数。

    具体实现函数,可以在其他模块中实现,然后在匿名函数中调用。

    示例,自动处理过期订单

    Order.php

        public static function handle_expired_order() {
            $orders = self::where('status', self::STATUS_NEW)
                ->whereRaw("created_at < NOW() - INTERVAL 1 DAY")
                ->get();
    
            foreach ($orders as $order) {
                $order->status = self::STATUS_EXPIRED;
                $order->save();
            }
        }
    

    app/Console/Kernel.php

    protected function schedule(Schedule $schedule)
        {
            $schedule->call(function () {
                Order::handle_expired_order();
            })->hourly();
        }
    

    每小时执行

    ->hourly();
    

    本地调试的时候,最好改成

    ->everyMinute();
    

    方便查看效果。

    最后不要忘了添加系统 crontab

    Ubuntu 下,命令行输入

    crontab -e
    

    然后在最后加入

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

    参考

  • 相关阅读:
    Springboot websocket学习Demo
    webpack与vue使用
    图片服务器图片剪切处理
    时间字段设置默认值
    函数的递归
    数据类型检测及封装
    隔行变色
    if-else案例–开关灯
    作用域
    数据类型核心操作步骤和原理
  • 原文地址:https://www.cnblogs.com/sgm4231/p/10189694.html
Copyright © 2011-2022 走看看