Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

486
Views
Los trabajos pendientes de Laravel Bus Batch son negativos

Estoy tratando de cargar productos de Shopify a través del caché y estoy usando Redis::throttle para evitar el límite de velocidad en Shopify. Mi problema es que puse todo el proceso de búsqueda en un Batch y devuelve un no negativo . de trabajos pendientes .

Aquí está la información del lote. ingrese la descripción de la imagen aquí

y aquí está mi enfoque

carga de función pública (Solicitud $ solicitud, Muestra $ muestra) {

 return DB::transaction(function () use ($sample) { $batch = Bus::batch([])->dispatch(); $since_id = 0; while ($since_id >= 0) { $fetchedProducts = (new ShopifyProduct( $sample->shopify_domain, $sample->shopify_info['access_token']) ) ->getById($since_id) ->then(function ($data) { return $data['products']; }, function () { return []; }) ->wait(); if (collect($fetchedProducts)->count() == 0) break; $lastProduct = Arr::last($fetchedProducts); $since_id = $lastProduct['id']; collect($fetchedProducts) ->each(function ($shopifyProduct) use($merchant, &$batch) { $batch->add(new CacheProducts($shopifyProduct, $sample)); }); } return $this->okResponse(['batch_id' => $batch->id]) ->header('Content-Type', 'application/vnd.api+json'); }); }

y aquí está el trabajo

 /** * Execute the job. * * @return void */ public function handle() { Redis::throttle("shopify-cache")->allow(30)->every(60)->block(70)->then(function () { (new Metafield( $this->merchant->shopify_domain, $this->merchant->shopify_info['access_token'] ) ) ->get($this->shopifyProduct['id'], 'products') ->then(function ($data) { $this->shopifyProduct['metafields'] = $data['metafields']; $cacheProducts = Cache::tags($this->merchant->name)->get('products') ?? []; array_push($cacheProducts, $this->shopifyProduct); Cache::tags($this->merchant->name)->put('products', $cacheProducts, now()->addHour()); }, function ($e) { }) ->wait(); }, function () { return $this->release(10); }); }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Debe refactorizar su código que está enviando los trabajos para comprender mejor qué está haciendo exactamente y para simplificar su código.

Además de eso, está despachando un lote vacío y más adelante en el ciclo está agregando trabajos al lote con $batch->add() , lo cual está totalmente bien, pero está pasando la variable &$batch en su cierre, lo cual, Creo que no está funcionando como esperabas.

¿Y qué $fetchedProducts ? lo está obteniendo por ID, pero lastId es la identificación del último elemento en esa matriz, ¿no es esa la misma identificación entonces?

Creo que lo ayudará si divide su código en partes y depura cada parte para verificar si los lotes de trabajo funcionan correctamente:

  1. Primero, asegúrese de que el identificador de su trabajo no haga nada más que regresar directamente ( return; ) para que pueda probar primero su clase de load .

     public function handle() { return; // All of the original code in this method you can comment out, for quicker testing. }
  2. Simplemente corte su método load() en partes, para que pueda verificar paso a paso si cada línea de código funciona como espera.

  3. Refactorice su código para comprender mejor lo que está sucediendo. Hice algunos cambios con la esperanza de que este código sea un poco más legible;

     return DB::transaction(function () use ($sample) { $jobs = []; // Fetch all products (if there are too many products, you may use paginated results) $fetchedProducts = (new ShopifyProduct( $sample->shopify_domain, $sample->shopify_info['access_token']) ) // Can you explain how $since_id can be different for each product if you are fetching products by that same id? //->getById($since_id) ->then(function ($data) { return $data['products']; }, function () { return []; })->wait(); if (collect($fetchedProducts)->empty()) { return $this->okResponse(['message' => 'No products to process.']) ->header('Content-Type', 'application/vnd.api+json'); } collect($fetchedProducts) ->each(function ($shopifyProduct) use($merchant, &$jobs) { $jobs[] = new CacheProducts($shopifyProduct, $sample) }); // After all jobs are added, we can dispatch them. $batch = Bus::batch($jobs)->dispatch(); return $this->okResponse(['batch_id' => $batch->id]) ->header('Content-Type', 'application/vnd.api+json'); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!