jeudi 24 octobre 2019

Laravel 5.5 Queue worker processes events fired from a job

In Laravel 5.5 I want to create a deferred PDF export job (MyExportingJob) and work it with a database queue-worker. When that job is finished, I want to fire an event (MyExportingJobComplete) which is then caught by a websocket client in order to download or view the exported file.

In my AppServiceProvider.php I have registered a Queue::after event handler (which feels hacky enough as it is).

Queue::after(function (JobProcessed $event) {
    if ($event->job->payload()['displayName'] === MyExportingJob::class) {
        event(new MyExportingJobComplete(unserialize($event->job->payload()['data']['command'])));
    }
});

I have a job MyExportingJob, which looks like this:

class MyExportingJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct()
    {
        // constructing
    }

    public function handle()
    {
        // handling
    }
}

and my event MyExportingJobComplete, which looks like this:

class MyExportingJobComplete implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public function __construct()
    {
        // constructing
    }

    public function broadcastOn()
    {
        return new PrivateChannel(/* stuff here */);
    }

    public function broadcastAs()
    {
        return 'MyExportingJobComplete';
    }
}

I'm running php artisan queue:work database --once in order to process the job. The job processes fine, file is generated and all is good, but when the MyExportingJob is done processing, a new processing is fired for the event itself.

Console output is:

[2019-10-24 10:40:41] Processing: MyNamespace\Jobs\MyExportingJob
[2019-10-24 10:40:45] Processing: MyNamespace\Events\MyExportingJobComplete
[2019-10-24 10:40:45] Processed:  MyNamespace\Events\MyExportingJobComplete
[2019-10-24 10:40:45] Processed:  MyNamespace\Jobs\MyExportingJob

This is where my problem arises. The job is, for some reason, being worked again so I now have a duplicate file generated... It's like the queue thinks the event is the job, I'm not even using any of the Queue-traits in my event.

Same thing happens when I try to fire the event from the job itself after it is done generating the file, instead of from the Queue::after closure (thought that would fix it, guess not).

What am I doing wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire