Create a unique background job
authorCyperghost <olaf_schmitz_1@t-online.de>
Wed, 21 Feb 2024 10:18:52 +0000 (11:18 +0100)
committerCyperghost <olaf_schmitz_1@t-online.de>
Wed, 21 Feb 2024 10:18:52 +0000 (11:18 +0100)
wcfsetup/install/files/lib/system/background/job/AbstractUniqueBackgroundJob.class.php [new file with mode: 0644]

diff --git a/wcfsetup/install/files/lib/system/background/job/AbstractUniqueBackgroundJob.class.php b/wcfsetup/install/files/lib/system/background/job/AbstractUniqueBackgroundJob.class.php
new file mode 100644 (file)
index 0000000..5c60ba3
--- /dev/null
@@ -0,0 +1,58 @@
+<?php
+
+namespace wcf\system\background\job;
+
+use wcf\system\background\BackgroundQueueHandler;
+
+/**
+ * @author      Olaf Braun
+ * @copyright   2001-2024 WoltLab GmbH
+ * @license     GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
+ * @since       6.1
+ */
+abstract class AbstractUniqueBackgroundJob extends AbstractBackgroundJob
+{
+    /**
+     * @inheritDoc
+     */
+    final public const MAX_FAILURES = 1;
+
+    /**
+     * Returns a unique identifier for this job.
+     *
+     * @return string
+     */
+    public function identifier(): string
+    {
+        return static::class;
+    }
+
+    #[\Override]
+    final public function perform()
+    {
+        $this->run();
+        if ($this->requeue()) {
+            BackgroundQueueHandler::getInstance()->enqueueIn($this);
+        }
+    }
+
+    /**
+     * Runs the job.
+     */
+    abstract protected function run(): void;
+
+    /**
+     * Returns whether this job should be queued again because it has more to do.
+     *
+     * @return bool
+     */
+    abstract protected function requeue(): bool;
+
+    #[\Override]
+    final public function onFinalFailure()
+    {
+        if ($this->requeue()) {
+            BackgroundQueueHandler::getInstance()->enqueueIn($this, $this->retryAfter());
+        }
+    }
+}