Sabonzy
7 months ago
170
3
Laravel

how to conditionally chain queue jobs

Posted 7 months ago by Sabonzy

I am using laravel-excel to export data to excel, it can take quiet a while to finish and sometimes timeout when the data is very large. I decided to break the export into smaller units and combine them later. The user needs to be notified when the whole process is complete. the problem is that the user gets notified upon every completed piece of the process. for instance if i break the export process into five pieces the user will be notified five times and that's not what i want, so i created another job and chained the user notification on but the problem with this is that the user get notified before the exports get completed.

Is There a way i can conditionally chain a job so they can run sequentially.

note am using queues for the process

  $pathToFile = Str::slug(auth()->user()->name).'/'.md5(collect(request()->query())->flatten());
            $masterExcelFileName = Str::slug(request()->user()->name.' '.md5(collect(request()->query())->flatten())).'.xlsx';
            $this->dispatch(
                (new  ProcessDownload($this->getGroup(), $this->getSubGroup(), $this->getDateFrom(),
                    $this->getDateTo(), request('system_name'), $pathToFile, $masterExcelFileName)
                )->chain([
                    new NotifyUserOfCompletedExport(request()->user(), $pathToFile, $masterExcelFileName),
                ])->allOnQueue('exports')
            );

ProcessDownload class

 public function handle()
        {
// only notify user when this whole process is completed

            collect($this->datePeriod())->chunk(7)->each(function (Collection $week) {
                $days = $week->map(function ($day) {
                    return $this->dayTimeRange($day);
                });
                $filename = Str::slug(sprintf('%s %s %s %s %s',
                        $week->first()->format('M j Y'),
                        'to',
                        $week->last()->format('M j Y'),
                        $this->group,
                        $this->subGroup)).'.xlsx';

                (new SmpWorkbookExport(
                    $this->group,
                    $this->subGroup,
                    $this->name,
                    $days
                ))->queue("$this->pathToFile/$filename", 'public', Excel::XLSX)
                    ->chain([
                        new  MergeWorkSheets($this->pathToFile,$filename,$this->masterExcelFileName)
                    ])
                    ->allOnQueue('exports');
            });

Please sign in or create an account to participate in this conversation.