任务调度

在环境中增加任务条目,使系统每分钟执行你laravel中的任务
sudo vim /etc/crontab

在最后一行加入这句话

    * * * * * root php /var/www/Cms/artisan schedule:run >> /dev/null 2>&1

在app\Console\Commands下面是php artisan命令的文件,现在我们也需要创建一个

php artisan make:console Test

Test.php 就可以看到了

class Test extends Command
{
/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'flashApi:start'; // 这里是命令

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

/**
 * Create a new command instance.
 *
 * @return void
 */

protected static $newsFlashService = null;

public function __construct(NewsFlashService $newsFlashService)
{
    parent::__construct();
    self::$newsFlashService = $newsFlashService;
}

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

/**
 * 接口数据获取
 *
 * @return array
 * @author jacklin
 */
public function getDataByTemApi()
{
    // 接口开关 默认为true
    $switch = Redis::get('STRING:FLASH:SWITCH:STATUS');
    if ($switch==2) return Common::returnResponse(411);

    // 执行自动添加接口
    $res = self::$newsFlashService->addDataByTemApi();
    Log::info('=======>快讯接口本次请求添加的数据条数为:');
    Log::info($res);
}
}

创建好这个文件,在根目录再执行php artisan 就可以看到我们这个命令,以及命令描述
然后,我们需要用linux的任务调度来执行这个命令,做法就是在app\Console\Kernel.php中注册这条命令,以及规定这条命令的执行频次。

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

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('flashApi:start')->everyMinute();// 定义命令每分钟执行
}
}

值得一说的是$schedule 不只有执行命令的command()方法,还有call()方法来执行某个控制器的某方法;

mac下面,不能用环境变量, 要写php 命令的绝对命令

本作品采用《CC 协议》,转载必须注明作者和本文链接
毛仔
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
wanghan

新建了Test,artsian里面看不见命令的签名啊?

5年前 评论
wanghan

看见了,command数组中忘写了

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!