prgrm
prgrm

Reputation: 3833

Getting a schedule job unstuck in Laravel

I have a schedule job that calls a function every time. This function does a lot of thing that perhaps throw an exception or gives me an error.

This is done in a loop, so if an error occurs, the function stops working and gets stucked until I delete the entry that is causing the error (or fix the error).

Something like this:

public function process_documents()
{
$documents = document::where("processed", 0)->get();

foreach($documents as $document)
{
$this->do_this($document);
$this->do_that($document);
$this->finish($document);
}

}

Solutions that I have though:

1- Make a command that executes a command.

foreach($documents as $document)
{
Artisan::call("document:process",$document->id);
}

2- try catch everywhere

I know they both would work but I would like to know if there is another way.

Upvotes: 0

Views: 132

Answers (2)

Luceos
Luceos

Reputation: 6730

The drawback of using commands inside commands is that you don't gain that much from it. You could actually just run the code inside the initial command and catch errors that way.

An alternative solution you can implement is running the code from inside the loop in a separate forked process, for instance by using symfony/process or duncan3dc/fork-helper.

Having implemented both of these with success for a use case similar to yours, it really depends on what your inner logic does. If the code can be ran simultaneously or not, forking the process allows you to keep your main process alive.

A small hint if you test this out, make sure to check db connections etc. These normally get lost during forking.

Upvotes: 1

Jerodev
Jerodev

Reputation: 33196

The best solution would be to find out why the process crashes and solve this problem. You could write some code that handles the error, stores the problem in the database and skips the document until the problem is resolved.

Otherwise, I believe that your first solution will be the best way to separate the processing of the different documents. Your code will also be much cleaner.
Try-catches would only clog up your code.

Upvotes: 1

Related Questions