laravel5.8 定时任务(每隔5s执行一次)

注意:laravel自带的定时任务最低1分钟执行一次,必须使用shell脚本

1:首先进入到laravel/app/console 目录下,Console 目录包含应用所有自定义的 Artisan 命令,这些命令类可以使用 make:command 命令生成。该目录下还有 Console/Kernel 类,在这里可以注册自定义的 Artisan 命令以及定义调度任务。

php artisan make:command Charge

2:创建完之后,打开console目录下的commands目录,我们会发现里面已经有了一个文件

<?php
/*
 * 定时任务---更新预约状态
 */
namespace App\Console\Commands;

use App\Models\Test;
use Illuminate\Console\Command;

class Charge extends Command
{
    /**
     * 此处代表laravel自动生成的名称,下面执行的时候能用到
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order_charge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'order_charge';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
         //具体业务操作
        \Log::info('预约订单更新状态');
         $ini['user_id'] = 1;
         $ini['add_time'] = date("Y-m-d H:i:s",time());
         Test::insert($ini);
    }
}

3、定时命令创建好之后,我们需要修改kernel.php文件

<?php

namespace App\Console;

use App\Console\Commands\Charge;
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 = [
        //定时任务的名称
        Charge::class
    ];

    /**
     *1、这个方法按照自己的需求,确定定时方法的执行顺序
     * Define the application's command schedule.
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('order_charge')->everyMinute();
    }

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

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

4:执行定时任务

a)在/root/shell/文件夹里面建个脚本文件 charge.sh

#!/bin/bash
step=5 #间隔的秒数
 
for (( i = 0; i < 60; i=(i+step) )); do
/usr/bin/php /www/wwwroot/ychongdian/artisan schedule:run  >> /home/shell/log/charge.log 2>&1
sleep $step
done
 
exit 0

第一个参数是php所在的位置 可以用 which php

第二个位置是项目的目录文件夹

b)脚本赋予执行的权限 chmod +x charge.sh

c)crontab -e 输入以下语句,然后:wq 保存退出。

* * * * * /root/shell/charge.sh

至此laravael定时任务完成

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值