phpdroid
phpdroid

Reputation: 1663

Laravel Not able to dispatch job from crontab

if i use this code in a controller queuing works well

 $job=(new ReProcessShipment($single_data->request_data))->delay(2);
 $this->dispatch($job);

but using same code in crontab error throws

Method App\Console\Commands\AddPreProcess::dispatch does not exist. {"exception":"[object] (BadMethodCallException(code: 0):
Method App\Console\Commands\AddPreProcess::dispatch does not exist.

tried to use it like

 $job=(new ReProcessShipment($single_data->request_data))->delay(2);
 ReProcessShipment::dispatch($job);

then get error

Object of class App\Jobs\ReProcessShipment could not be converted to string {"exception":"[object] (ErrorException(code: 0): Object of class App\Jobs\ReProcessShipment could not be converted to string at

am not able to process job queue from a cronjob any suggestion would be great.

Upvotes: 3

Views: 1939

Answers (1)

D Malan
D Malan

Reputation: 11454

You can dispatch a job by calling static dispatch method on the job class and passing the job's constructor arguments to the dispatch method, like this:

ReProcessShipment::dispatch($single_data->request_data)->delay(2);

Ensure that you are using the Illuminate\Foundation\Bus\Dispatchable trait to be able to call dispatch on the job class, e.g.:

use Illuminate\Foundation\Bus\Dispatchable;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, ...

If you have a look at the source you'll see that the static dispatch function creates the job for you using the job's parameters, so you don't need to create the job before you dispatch it. This is the source of the dispatch function:

public static function dispatch()
{
    return new PendingDispatch(new static(...func_get_args()));
}

So it essentially transforms this:

ReProcessShipment::dispatch($single_data->request_data);

into this:

new PendingDispatch(new ReProcessShipment($single_data->request_data));

Upvotes: 2

Related Questions