@@ -42,6 +42,20 @@ class QueueWorker
4242 */
4343 protected $ maxMemory = 128 ;
4444
45+ /**
46+ * The maximum number of jobs to process.
47+ *
48+ * @var int|null
49+ */
50+ protected $ maxJobs = null ;
51+
52+ /**
53+ * The number of jobs processed.
54+ *
55+ * @var int
56+ */
57+ protected $ jobsProcessed = 0 ;
58+
4559 /**
4660 * Callback to be executed **before** a job is processed.
4761 *
@@ -109,6 +123,12 @@ public function daemon(string $queue = 'default', array $options = []): void
109123 break ;
110124 }
111125
126+ // Check if max jobs limit reached
127+ if ($ this ->maxJobsReached ()) {
128+ $ this ->stop (0 , "Maximum job limit of {$ this ->maxJobs } reached " );
129+ break ;
130+ }
131+
112132 // Check memory usage
113133 if ($ this ->memoryExceeded ()) {
114134 $ this ->stop (12 , 'Memory limit exceeded ' );
@@ -143,6 +163,7 @@ protected function processNextJob(string $queue): void
143163 }
144164
145165 $ this ->processJob ($ queueJob );
166+ $ this ->jobsProcessed ++;
146167 } catch (\Throwable $ e ) {
147168 $ this ->handleWorkerException ($ e );
148169 $ this ->sleep ($ this ->sleep );
@@ -261,6 +282,16 @@ protected function shouldQuit(): bool
261282 return $ this ->shouldQuit ;
262283 }
263284
285+ /**
286+ * Determine if the maximum number of jobs has been reached.
287+ *
288+ * @return bool
289+ */
290+ protected function maxJobsReached (): bool
291+ {
292+ return !empty ($ this ->maxJobs ) && $ this ->jobsProcessed >= $ this ->maxJobs ;
293+ }
294+
264295 /**
265296 * Stop the worker.
266297 *
@@ -352,6 +383,8 @@ protected function configureOptions(array $options): void
352383 if (isset ($ options ['maxExecutionTime ' ])) {
353384 $ this ->maxExecutionTime = (int ) $ options ['maxExecutionTime ' ];
354385 }
386+
387+ $ this ->maxJobs = $ options ['maxJobs ' ] ?? null ;
355388 }
356389
357390 /**
@@ -408,4 +441,25 @@ public function setMaxExecutionTime(int $seconds): void
408441 {
409442 $ this ->maxExecutionTime = $ seconds ;
410443 }
444+
445+ /**
446+ * Set the maximum number of jobs to process.
447+ *
448+ * @param int|null $maxJobs
449+ * @return void
450+ */
451+ public function setMaxJobs (?int $ maxJobs ): void
452+ {
453+ $ this ->maxJobs = $ maxJobs ;
454+ }
455+
456+ /**
457+ * Get the number of jobs processed.
458+ *
459+ * @return int
460+ */
461+ public function getJobsProcessed (): int
462+ {
463+ return $ this ->jobsProcessed ;
464+ }
411465}
0 commit comments