Laravel定时任务

方式一:闭包(schedule方法添加)
protected function schedule(Schedule $schedule)
    {
        $schedule->call(function (){
            DB::update("UPDATE express_logistics set logistics_status=19 WHERE logistics_status=3 AND direction='song'
and DATE_ADD(user_qianshou_time,INTERVAL 15 day) <= NOW() and DATE_ADD(user_qianshou_time,INTERVAL 15 day)>=user_qianshou_time");
        })->daily();
    }

方式二:command 方法通过命令名或类来调度一个 Artisan 命令

第一步:
执行php artisan make:command OrderComment(尾部为源代码),创建文件
第二步:编辑文件OrderComment.php文件
定义名称:
protected $signature = 'orderComment';
添加描述(这一步可有可无)
protected $description = '15天内,客户签收未评价订单,更改物流状态为19';
需要执行的方法写在handle里面。
public function handle()
    {
        //
        $this->logisticsList();
    }
方法:
public function logisticsList()
    {
        $ExpressLogistics = ExpressLogistics::select('id','logistics_status','user_qianshou_time')
            ->where('logistics_status',3)->get();
        $idS = [];
        foreach ($ExpressLogistics as $logistic) {
            $signTime = strtotime($logistic->user_qianshou_time);
            $currentTime = time();
            $day = ceil(($currentTime-$signTime)/86400);
            if ($day >Constant::DAY) {
                if (Constant::COMMENT == 1) {
                    CommentOrder::dispatch($logistic->id);
                } else {
                    array_push($idS,$logistic->id);
                }
            }
        }
        if (Constant::COMMENT != 1 && !empty($idS)) {
            $this->updateStatus($idS);
        }
    }
第三步:注册路由命令
protected $commands = [
//
\App\Console\Commands\OrderComment::class,
];
第四步:在schedule方法中定义执行时间,可以是指定的时间,也可以是每分、每时、每天
protected function schedule(Schedule $schedule)
{
$schedule->command('comment')->days();
}
第五步:要实现定时任务还得让程序自动执行(方式一或方式二,5和6均需执行)
crontab -e编辑文件
crontab -l 显示crontab 文件
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
第六步:命令行输入 php artisan schedule:run 即可执行任务
方式一源码:
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $schedule->call(function (){
            DB::update("UPDATE express_logistics set logistics_status=19 WHERE logistics_status=3 AND direction='song'
and DATE_ADD(user_qianshou_time,INTERVAL 15 day) <= NOW() and DATE_ADD(user_qianshou_time,INTERVAL 15 day)>=user_qianshou_time");
        })->daily();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
View Code

方式二源码:

Kernel文件源码

<?php

namespace App\Console;

use App\Console\Commands\OrderComment;
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 = [
        //
        OrderComment::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('orderComment')->daily();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
View Code
OrderComment源码
<?php

namespace App\Console\Commands;

use App\Jobs\CommentOrder;
use App\Models\Api\ExpressLogistics;
use App\Tools\Constant;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class OrderComment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orderComment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '15天内,客户签收未评价订单,更改物流状态为19';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $this->logisticsList();
    }

    public function logisticsList()
    {
        $ExpressLogistics = ExpressLogistics::select('id','logistics_status','user_qianshou_time')
            ->where('logistics_status',3)->get();
        $idS = [];
        foreach ($ExpressLogistics as $logistic) {
            $signTime = strtotime($logistic->user_qianshou_time);
            $currentTime = time();
            $day = ceil(($currentTime-$signTime)/86400);
            if ($day >Constant::DAY) {
                if (Constant::COMMENT == 1) {
                    CommentOrder::dispatch($logistic->id);
                } else {
                    array_push($idS,$logistic->id);
                }
            }
        }
        if (Constant::COMMENT != 1 && !empty($idS)) {
            $this->updateStatus($idS);
        }
    }

    public function updateStatus($idS)
    {
        DB::table('express_logistics')->whereIn('id',$idS)->update(['logistics_status'=>19]);
    }
}
View Code

队列

<?php

namespace App\Jobs;

use App\Models\Api\ExpressLogistics;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class CommentOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $id;
    public function __construct($id)
    {
        //
        $this->id = $id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $this->updateStatus($this->id);
    }

    /**
     * @param $id 物流表ID
     * @description 15天内未评价订单,订单状态更改为19
     * @auther caoxiaobin
     */
    public function updateStatus($id)
    {
        $logistics = ExpressLogistics::find($id);
        $logistics->logistics_status=19;
        $logistics->save();
    }
}
View Code

常用常量

<?php
/**
 * Created by PhpStorm.
 * User: yaoyao
 * Date: 2018/2/28
 * Time: 15:32
 */

namespace App\Tools;

class Constant
{
    const OK = "10000";  //接口调用成功
    const ERROR = "20000"; //发生错误 服务不可用
    const NOTPAY = "20001"; //没支付
    const SHANG_GUAED = "20002"; //已上挂
    const REFUSED = "20004"; //已拒绝
    const WULIUED = "20005"; //已打印物流单

    const WARRE_ERROR = "-9527"; //发生错误 token失效

    const SUCCESS = "SUCCESS";
    const FAIL ="ERROR";
    const ADMIN_SESSION = "Admin_Session";
    const ADMIN_SESSION_ID = "Admin_Session_ID";
    const  SESSION_MENU = 'SessionMenu';
    const SERVICE_CATEGORIES='service_categories';

    const EXPRICE_TIME = 86400*60;//有效期
    const EXPRICE_TIME_TEST = 1;//测试有效期

    const EXPRICE_FIVE_HOURS = 18000;//5小时的有效期

    //const TEST_SERVER_HOST="http://edxpay07.edaixi.cn:81/";     //测试域名
    const TEST_SERVER_HOST="http://edxpay.edaixi.com/";     //正式域名
    const COMMENT=1;//定时任务十分开启队列  1表示开启队列 0表示不开启
    const DAY=15;//多少天之内未评论,开启自动评价
}
View Code

posted on 2019-02-16 16:00  LOVESTYUDY  阅读(186)  评论(0编辑  收藏  举报

导航