使用Laravel 5.6运行cronjob(使用Scheduler) [英] Running a cronjob with Laravel 5.6 (using the Scheduler)

查看:83
本文介绍了使用Laravel 5.6运行cronjob(使用Scheduler)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一些任务应按设置的时间间隔自动运行.因此,我立即想到:我可以在服务器上执行cron作业.

In my application, I have a few tasks that should run automatically at set intervals. So my immediate thought was: I could make a cron job on the server.

我已经开始阅读一些文章:

I have got myself started by reading a few articles:

  • Setting up cronjobs in Laravel - https://scotch.io/@Kidalikevin/how-to-set-up-cron-job-in-laravel
  • The difference between normal cronjobs and the Laravel way - https://code.tutsplus.com/tutorials/tasks-scheduling-in-laravel--cms-29815
  • This article on what path\to\artisan actually means - https://laracasts.com/discuss/channels/laravel/pathtoartisan-where-it-is

以及有关计划的Laravel文档.

As well as the Laravel documentation on scheduling.

我正在尝试将Facebook和Twitter帖子从API提取到数据库中.

I'm attempting to have Facebook and Twitter posts pull into a database from an API.

更新Facebook和Twitter

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

use App\Article;
use App\TwitterPost;
use App\FacebookPost;
use Twitter;

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

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = 'Updates facebook and twitter feeds to DB';

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

  public function updateFacebook()
  {

      //Access token
      $access_token = 'secret';
      //Request the public posts.
      $json_str = file_get_contents('https://graph.facebook.com/v3.0/NewableGroup/feed?access_token='.$access_token);
      //Decode json string into array
      $facebookData = json_decode($json_str);

      //For each facebook post
      foreach($facebookData->data as $data){

          //Convert provided date to appropriate date format
          $fbDate = date("Y-m-d H:i:s", strtotime($data->created_time));
          $fbDateToStr = strtotime($fbDate);

          //If a post contains any text
          if(isset($data->message)){

            //Create new facebook post if it does not already exist in the DB
            $facebookPost = FacebookPost::firstOrCreate(
                  ['post_id' => $data->id], ['created_at' => $fbDateToStr, 'content' => $data->message, 'featuredImage' => null]
            );

            //Output any new facebook posts to the console.
            if($facebookPost->wasRecentlyCreated){
                $this->info("New Facebook Post Added --- " . $facebookPost->content);
             }

          }

      }

  }

  public function updateTwitter($amount)
  {

      $twitterData = Twitter::getUserTimeline(['count' => $amount, 'tweet_mode'=>'extended', 'format' => 'array']);

      foreach($twitterData as $data){

          //Convert provided date to appropriate date format
          $tweetDate = date("Y-m-d H:i:s", strtotime($data['created_at']));
          $tweetDateToStr = strtotime($tweetDate);
          $tweetImg = null;

          //Get the twitter image if any
          if(!empty($data['extended_entities']['media']))
          {
              foreach($data['extended_entities']['media'] as $v){
                  $tweetImg = $v['media_url'];
              }
          }

          //Create new tweet if it does not already exist in the DB
          $twitterPost = TwitterPost::firstOrCreate(
              ['post_id' => $data['id']], ['created_at' => $tweetDateToStr, 'content' => $data['full_text'], 'featuredImage' => $tweetImg]
          );

          //Output any new twitter posts to the console.
          if($twitterPost->wasRecentlyCreated){
             $this->info("New Tweet Added --- " . $twitterPost->content);
          }

      }

  }

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

这是Laravel中的控制台命令,已在Kernal.php

This is a console command within Laravel, which is registered in Kernal.php

<?php

namespace App\Console;

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 = [
        'App\Console\Commands\UpdateSocial'
    ];

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

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

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

这使我可以运行命令:php artisan update:social,但是,很明显,要自动执行此操作,我需要在服务器上设置cron作业.

Which enables me to run the command: php artisan update:social, but, evidently for this to happen automatically I need to set up a cron job on the server.

文档在某些地方重复了这一行:

The documentation repeats this line in a few places:

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

我知道* * * * *相当于每天的每一分钟,而schedule:run很不言而喻,但是最后一部分是什么?

I know that * * * * * is the equivalent of every minute of every day and schedule:run is pretty self-explanatory but what is the last part?

这部分专门:

>> /dev/null 2>&1

而且,即使它仅每10分钟运行一次,为什么还要在服务器上每分钟运行一次?

Also, why must it run every minute on the server even though it'll only run every 10 minutes anyway?

还可以使用相同的设置在诸如xxamp的本地服务器上运行这些作业吗?

Also, can you use the same setup to run these jobs on a local server like xxamp?

更新

另一个用户提供了一个很棒的链接:

Another user provided a greate link: https://unix.stackexchange.com/questions/163352/what-does-dev-null-21-mean-in-this-article-of-crontab-basics

这很好地解释了cronjob命令的最后一部分.

This explains the final part of the cronjob command nicely.

图片供参考:

推荐答案

您正在使用xamp,所以我假设您在Windows上.我建议您下载并安装 https://sourceforge.net/projects/cronw/ 然后,您可以使用Unix风格的cronjobs来运行作业.

You're using xamp, so I assume you're on windows. I suggest you download and install https://sourceforge.net/projects/cronw/ Then you can use unix style cronjobs to run your jobs.

您也可以考虑使用Windows任务计划程序,但是在我看来,使用cron计划程序效果更好,因为Windows任务计划程序每5分钟仅允许触发一次.

You can also look into using the windows task scheduler, but using the cron scheduler works better in my opinion because the windows task scheduler only allows once per 5 minute triggers.

您还需要按照INSTALL文件中的说明进行启动和运行.但是,一旦运行,就像unix crontab的

You'll also need to follow the instructions in the INSTALL file to get cronw up and running. But once it runs it's very easy to manage just like unix crontab's

您每分钟运行 Laravel计划程序,但是Laravel计划程序随后会调查需要按计划运行.

You run the Laravel scheduler every minute, but the Laravel scheduler then looks into what needs to be run in it's schedule.

您有Cron触发了调度程序.
然后您的调度程序将其加载为作业.
迭代那些并过滤掉尚未调度的
执行易调度的作业.

You have Cron triggering your scheduler.
Then your scheduler loads it's jobs.
It iterates those and filters out that are not scheduled yet
Eglible scheduled jobs are executed.

Cron只是启动调度程序以查看是否有任何可能运行的待处理作业的一种方法.

Cron is just a way to kick the scheduler to see if there are any pending jobs eglible to be run.

如果您只想运行artisan命令而不使用调度程序服务,则不必每分钟运行一次,但是可以让cron作业每10分钟运行一次.

If you just wish to run artisan commands and not use the scheduler service you don't need to run every minute, but you can let the cron job run every 10 minutes.

我个人建议执行一个调度程序作业,因为这样您就可以如果前一个进程尚未完成,则它不会执行,从而停止两个进程同时执行.

Personally i'd advice a scheduler job to be run, since you can then have it not execute if the previous process hasn't finished yet, stopping two processes executing simultaneously.

>> /dev/null 2>&1如链接 rkj 进行评论,这是一种防止自动电子邮件作为状态报告发送给您的简单方法.

The >> /dev/null 2>&1 is as posted in the link https://unix.stackexchange.com/questions/163352/what-does-dev-null-21-mean-in-this-article-of-crontab-basics as a comment by rkj a simple way to prevent an automatic email to be sent to you as a status report.

这篇关于使用Laravel 5.6运行cronjob(使用Scheduler)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆