Josh Miller
Josh Miller

Reputation: 23

How to schedule Laravel 5 job to get data from external JSON file, and store value in database?

I'm currently working on a project in Laravel, and I want to schedule a job that grabs a value (the price of Bitcoin) from an external API (JSON file) and stores this value in my database every few minutes.

So far, I have created a job using the artisan command: artisan make:job UpdateBitcoinMarketPrice. But I've no idea what to include in my public function handle() in side of the Job class that was created.

I have fathomed that I can call this job regularly from App\Console\Kernel.php with the following function:

protected function schedule(Schedule $schedule){ // $schedule->command('inspire') // ->hourly(); $schedule->job(new UpdateBitcoinMarketPrice)->everyFiveMinutes();}

Should I, for example, create a new Model that stores said value? Then create a new Object every-time this run?

Should I then call the first row of the database should I wish to return the value?

Upvotes: 1

Views: 1607

Answers (1)

Leo
Leo

Reputation: 7420

Job classes are very simple, normally containing only a handle() method which is called when the job is processed by the queue. You can use the contructor to inject any parameter or serialize a model so you can use it in your handle method.

So to keep it bold you can make the api call on the handle method and store the response in the databse. Knowing that this is going to fire the api call as a background job.

Something along the lines of:

    public function __construct(User $user)
    {
         //In this case Laravel serilizes the User model example so you could use it on your background job. 
         //This can be anything that you need in order to make the call
        $this->user = $user;
    }

    //Injecting as an example ExtrernalServieClass or Transformer(to transform api response).
    public function handle(ExternalServiceClass $service, Transformer $transform)
    { 

         //Here you can make the call to the api. 

         //Get the response parse it 

         // Store to database 

         $response = $service->postRequest($someUri, $someParams);

         $parsedResponse = $transform->serviceResponse($response);

         DatabaseModel::firstOrCreate($parsedResponse);

    }

}

The handle method is called when the job is processed by the queue. Note that you are able to type-hint dependencies on the handle method of the job, like in the example above. The Laravel service container automatically injects these dependencies.

Now since you are going to run the job everyFiveMinutes() you have to be careful since if the previous job is not completed by default, scheduled tasks will be run even if the previous instance of the task is still running.

To prevent this, you may use the withoutOverlapping method:

$schedule->job(new UpdateBitcoinMarketPrice)->everyFiveMinutes()->>withoutOverlapping();

Upvotes: 1

Related Questions