From 436fda8b40b3931ace8a6db753b044c6af294fb3 Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Tue, 14 Feb 2023 12:06:57 +0100
Subject: [PATCH] cron: add a "--force" option to the cron command

This will force run all cron commands even if they aren't due.
This can be helpful in case of development/debugging.

And we want to change the default of cron not running at the
beginning when the state/cache is missing i.e. when the api
is re-deployed. This allows the admin to force a run in case
it is known that the api was offline for some time and cron
jobs are needed.
---
 src/Cron/CronCommand.php | 11 +++++++++--
 src/Cron/CronManager.php |  8 ++++++++
 2 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/src/Cron/CronCommand.php b/src/Cron/CronCommand.php
index cf5b996..521484d 100644
--- a/src/Cron/CronCommand.php
+++ b/src/Cron/CronCommand.php
@@ -10,6 +10,7 @@ use Psr\Log\LoggerAwareTrait;
 use Psr\Log\NullLogger;
 use Symfony\Component\Console\Command\Command;
 use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
 use Symfony\Component\Console\Output\OutputInterface;
 
 final class CronCommand extends Command implements LoggerAwareInterface
@@ -34,19 +35,25 @@ final class CronCommand extends Command implements LoggerAwareInterface
     protected function configure()
     {
         $this->setDescription('Runs various tasks which need to be executed periodically');
+        $this->addOption('force', null, InputOption::VALUE_NONE, 'Run the cron job even if it\'s not due');
     }
 
     protected function execute(InputInterface $input, OutputInterface $output): int
     {
         // We need to pass the prune command to CachePrune since I didn't find an alternative
         $app = $this->getApplication();
+        $force = $input->getOption('force');
         assert($app !== null);
         $command = $app->find('cache:pool:prune');
         CachePrune::setPruneCommand($command);
 
         // Now run all jobs
-        $dueJobs = $this->manager->getDueJobs();
-        foreach ($dueJobs as $job) {
+        if ($force) {
+            $jobsToRun = $this->manager->getAllJobs();
+        } else {
+            $jobsToRun = $this->manager->getDueJobs();
+        }
+        foreach ($jobsToRun as $job) {
             $name = $job->getName();
             $this->logger->info("cron: Running '$name'");
             try {
diff --git a/src/Cron/CronManager.php b/src/Cron/CronManager.php
index 40ef666..de6a24a 100644
--- a/src/Cron/CronManager.php
+++ b/src/Cron/CronManager.php
@@ -85,6 +85,14 @@ final class CronManager implements LoggerAwareInterface
         return $previousRun;
     }
 
+    /**
+     * @return CronJobInterface[]
+     */
+    public function getAllJobs(): array
+    {
+        return $this->jobs;
+    }
+
     /**
      * @return CronJobInterface[]
      */
-- 
GitLab