laravel定时任务怎么写?

8 篇文章 0 订阅

第一步:用PHP命令创建你想要执行的任务的文件,用 php artisan make:command 后面加上名称然后回车,看到successfully说明创建成功;

执行完成后在app/console/commands文件夹中就会看到创建的文件

 

第二步:点击文件名称,编辑文件写上需要执行的程序:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Service\Basket\BasketService;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '这是一个定时任务';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $res = BasketService::BasketOrderCommission();
        echo json_encode($res,JSON_UNESCAPED_UNICODE);
    }
}

第三步:将写好的任务在kernel文件中进行注册:

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log;
use App\Service\Purchasing\PurchasingService;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Testcommand::class,
        Commands\train::class,
        Commands\test::class,
        Commands\BasketOrderCommission::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        Log::info('【开始执行定时任务】time:'.date('Y-m-d H:i:s'));
        $schedule->command('BasketOrderCommission')->everyTenMinutes();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

第四步:注册成功后,用PHP命令执行一下任务,看看能不能跑通:php artisan +任务名称,即可单独运行任务

第五步:执行没问题了,在crontab命令中加入定时任务执行命令:crontab -e 回车

 编辑定时任务命令:

关于 >/dev/null 2>&1 的解释:

0表示键盘输入

1表示标准输出

2表示错误输出.

 编辑好以后保存退出,查看crontab命令:crontab -l

 最后,十分钟或者一分钟执行一次,看日志记录看看执行情况就好了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值