29.07.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Queues 314<br />

.<br />

In this example, note that we were able to pass an Eloquent model directly into the queued job’s<br />

constructor. Because of the SerializesModels trait that the job is using, Eloquent models will be<br />

gracefully serialized and unserialized when the job is processing. If your queued job accepts an<br />

Eloquent model in its constructor, only the identifier for the model will be serialized onto the queue.<br />

When the job is actually handled, the queue system will automatically re-retrieve the full model<br />

instance from the database. It’s all totally transparent to your application and prevents issues that<br />

can arise from serializing full Eloquent model instances.<br />

The handle method is called when the job is processed by the queue. Note that we are able to typehint<br />

dependencies on the handle method of the job. The Laravel service container automatically<br />

injects these dependencies.<br />

When Things Go Wrong<br />

If an exception is thrown while the job is being processed, it will automatically be released back<br />

onto the queue so it may be attempted again. The job will continue to be released until it has been<br />

attempted the maximum number of times allowed by your application. The number of maximum<br />

attempts is defined by the --tries switch used on the queue:listen or queue:work Artisan jobs.<br />

More information on running the queue listener can be found below.<br />

Manually Releasing Jobs<br />

If you would like to release the job manually, the InteractsWithQueue trait, which is already<br />

included in your generated job class, provides access to the queue job release method. The release<br />

method accepts one argument: the number of seconds you wish to wait until the job is made available<br />

again:<br />

.<br />

1 public function handle(Mailer $mailer)<br />

2 {<br />

3 if (condition) {<br />

4 $this->release(10);<br />

5 }<br />

6 }<br />

Checking The Number Of Run Attempts<br />

As noted above, if an exception occurs while the job is being processed, it will automatically be<br />

released back onto the queue. You may check the number of attempts that have been made to run<br />

the job using the attempts method:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!