Add functionality so that Scheduled tasks can be disabled (halted)

Created on 11 May 2023, over 1 year ago

Problem/Motivation

Currently it is not possible to simply disable a Scheduled Task to stop it running. The best you can do is to just set the next run date sometime far ahead. If you have complicated scheduled tasks you don't want to have to delete them when you don't want them to run for the foreseeable future.

Proposed resolution

I have added a new halt method to Drupal\webform_scheduled_tasks\Form\WebformScheduledTaskForm:

diff --git a/src/Form/WebformScheduledTaskForm.php b/src/Form/WebformScheduledTaskForm.php
index 46c6742..e582baf 100644
--- a/src/Form/WebformScheduledTaskForm.php
+++ b/src/Form/WebformScheduledTaskForm.php
@@ -107,6 +107,15 @@ class WebformScheduledTaskForm extends EntityForm {
           ],
         ];
       }
+      else {
+        $form['scheduled_task_info']['children']['halt'] =  [
+          '#type' => 'submit',
+          '#value' => t('Halt task'),
+          '#description' => t('Halt this task to stop it running.'),
+          '#submit' => ['::submitForm', '::halt'],
+          '#button_type' => 'danger',
+        ];
+      }
 
       $form['schedule_settings'] = [
         '#type' => 'details',
@@ -213,6 +222,34 @@ class WebformScheduledTaskForm extends EntityForm {
     $schedule->resume();
   }
 
+  /**
+   * Form submission handler for the 'halt' action.
+   *
+   * Halts a scheduled task from running until it is resumed again using ::resume.
+   *
+   * @param array $form
+   *   An associative array containing the structure of the form.
+   * @param \Drupal\Core\Form\FormStateInterface $form_state
+   *   The current state of the form.
+   */
+  public function halt(array $form, FormStateInterface $form_state) {
+    $user = \Drupal::currentUser();
+
+    /** @var \Drupal\webform_scheduled_tasks\Entity\WebformScheduledTaskInterface $schedule */
+    $schedule = $this->entity;
+
+    // Halt the task.
+    $schedule->halt(
+      $this->t(
+        'Disabled by @user at @now.',
+        [
+          '@user' => $user->getDisplayName(),
+          '@now' => date('c'),
+        ]
+      )
+    );
+  }
+
   /**
    * Create a plugin sub-form.
    *
✨ Feature request
Status

Active

Component

Code

Created by

πŸ‡¬πŸ‡§United Kingdom altcom_neil

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024