[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/plugins/task/demotasks/src/Extension/ -> DemoTasks.php (source)

   1  <?php
   2  
   3  /**
   4   * @package     Joomla.Plugins
   5   * @subpackage  Task.DemoTasks
   6   *
   7   * @copyright   (C) 2021 Open Source Matters, Inc. <https://www.joomla.org>
   8   * @license     GNU General Public License version 2 or later; see LICENSE.txt
   9   */
  10  
  11  namespace Joomla\Plugin\Task\DemoTasks\Extension;
  12  
  13  use Joomla\CMS\Plugin\CMSPlugin;
  14  use Joomla\Component\Scheduler\Administrator\Event\ExecuteTaskEvent;
  15  use Joomla\Component\Scheduler\Administrator\Task\Status;
  16  use Joomla\Component\Scheduler\Administrator\Task\Task;
  17  use Joomla\Component\Scheduler\Administrator\Traits\TaskPluginTrait;
  18  use Joomla\Event\SubscriberInterface;
  19  
  20  // phpcs:disable PSR1.Files.SideEffects
  21  \defined('_JEXEC') or die;
  22  // phpcs:enable PSR1.Files.SideEffects
  23  
  24  /**
  25   * A demo task plugin. Offers 3 task routines and demonstrates the use of {@see TaskPluginTrait},
  26   * {@see ExecuteTaskEvent}.
  27   *
  28   * @since 4.1.0
  29   */
  30  final class DemoTasks extends CMSPlugin implements SubscriberInterface
  31  {
  32      use TaskPluginTrait;
  33  
  34      /**
  35       * @var string[]
  36       * @since 4.1.0
  37       */
  38      private const TASKS_MAP = [
  39          'demoTask_r1.sleep'                    => [
  40              'langConstPrefix' => 'PLG_TASK_DEMO_TASKS_TASK_SLEEP',
  41              'method'          => 'sleep',
  42              'form'            => 'testTaskForm',
  43          ],
  44          'demoTask_r2.memoryStressTest'         => [
  45              'langConstPrefix' => 'PLG_TASK_DEMO_TASKS_STRESS_MEMORY',
  46              'method'          => 'stressMemory',
  47          ],
  48          'demoTask_r3.memoryStressTestOverride' => [
  49              'langConstPrefix' => 'PLG_TASK_DEMO_TASKS_STRESS_MEMORY_OVERRIDE',
  50              'method'          => 'stressMemoryRemoveLimit',
  51          ],
  52          'demoTask_r4.resumable' => [
  53              'langConstPrefix' => 'PLG_TASK_DEMO_TASKS_RESUMABLE',
  54              'method'          => 'resumable',
  55              'form'            => 'testTaskForm',
  56          ],
  57      ];
  58  
  59      /**
  60       * @var boolean
  61       * @since 4.1.0
  62       */
  63      protected $autoloadLanguage = true;
  64  
  65      /**
  66       * @inheritDoc
  67       *
  68       * @return string[]
  69       *
  70       * @since 4.1.0
  71       */
  72      public static function getSubscribedEvents(): array
  73      {
  74          return [
  75              'onTaskOptionsList'    => 'advertiseRoutines',
  76              'onExecuteTask'        => 'standardRoutineHandler',
  77              'onContentPrepareForm' => 'enhanceTaskItemForm',
  78          ];
  79      }
  80  
  81      /**
  82       * Sample resumable task.
  83       *
  84       * Whether the task will resume is random. There's a 40% chance of finishing every time it runs.
  85       *
  86       * You can use this as a template to create long running tasks which can detect an impending
  87       * timeout condition, return Status::WILL_RESUME and resume execution next time they are called.
  88       *
  89       * @param   ExecuteTaskEvent  $event  The event we are handling
  90       *
  91       * @return  integer
  92       *
  93       * @since   4.1.0
  94       * @throws  \Exception
  95       */
  96      private function resumable(ExecuteTaskEvent $event): int
  97      {
  98          /** @var Task $task */
  99          $task    = $event->getArgument('subject');
 100          $timeout = (int) $event->getArgument('params')->timeout ?? 1;
 101  
 102          $lastStatus = $task->get('last_exit_code', Status::OK);
 103  
 104          // This is how you detect if you are resuming a task or starting it afresh
 105          if ($lastStatus === Status::WILL_RESUME) {
 106              $this->logTask(sprintf('Resuming task %d', $task->get('id')));
 107          } else {
 108              $this->logTask(sprintf('Starting new task %d', $task->get('id')));
 109          }
 110  
 111          // Sample task body; we are simply sleeping for some time.
 112          $this->logTask(sprintf('Starting %ds timeout', $timeout));
 113          sleep($timeout);
 114          $this->logTask(sprintf('%ds timeout over!', $timeout));
 115  
 116          // Should I resume the task in the next step (randomly decided)?
 117          $willResume = random_int(0, 5) < 4;
 118  
 119          // Log our intention to resume or not and return the appropriate exit code.
 120          if ($willResume) {
 121              $this->logTask(sprintf('Task %d will resume', $task->get('id')));
 122          } else {
 123              $this->logTask(sprintf('Task %d is now complete', $task->get('id')));
 124          }
 125  
 126          return $willResume ? Status::WILL_RESUME : Status::OK;
 127      }
 128  
 129      /**
 130       * @param   ExecuteTaskEvent  $event  The `onExecuteTask` event.
 131       *
 132       * @return integer  The routine exit code.
 133       *
 134       * @since 4.1.0
 135       * @throws Exception
 136       */
 137      private function sleep(ExecuteTaskEvent $event): int
 138      {
 139          $timeout = (int) $event->getArgument('params')->timeout ?? 1;
 140  
 141          $this->logTask(sprintf('Starting %d timeout', $timeout));
 142          sleep($timeout);
 143          $this->logTask(sprintf('%d timeout over!', $timeout));
 144  
 145          return Status::OK;
 146      }
 147  
 148      /**
 149       * Standard routine method for the memory test routine.
 150       *
 151       * @param   ExecuteTaskEvent  $event  The `onExecuteTask` event.
 152       *
 153       * @return integer  The routine exit code.
 154       *
 155       * @since 4.1.0
 156       * @throws Exception
 157       */
 158      private function stressMemory(ExecuteTaskEvent $event): int
 159      {
 160          $mLimit = $this->getMemoryLimit();
 161          $this->logTask(sprintf('Memory Limit: %d KB', $mLimit));
 162  
 163          $iMem = $cMem = memory_get_usage();
 164          $i    = 0;
 165  
 166          while ($cMem + ($cMem - $iMem) / ++$i <= $mLimit) {
 167              $this->logTask(sprintf('Current memory usage: %d KB', $cMem));
 168              ${"array" . $i} = array_fill(0, 100000, 1);
 169          }
 170  
 171          return Status::OK;
 172      }
 173  
 174      /**
 175       * Standard routine method for the memory test routine, also attempts to override the memory limit set by the PHP
 176       * INI.
 177       *
 178       * @param   ExecuteTaskEvent  $event  The `onExecuteTask` event.
 179       *
 180       * @return integer  The routine exit code.
 181       *
 182       * @since 4.1.0
 183       * @throws Exception
 184       */
 185      private function stressMemoryRemoveLimit(ExecuteTaskEvent $event): int
 186      {
 187          $success = false;
 188  
 189          if (function_exists('ini_set')) {
 190              $success = ini_set('memory_limit', -1) !== false;
 191          }
 192  
 193          $this->logTask('Memory limit override ' . $success ? 'successful' : 'failed');
 194  
 195          return $this->stressMemory($event);
 196      }
 197  
 198      /**
 199       * Processes the PHP ini memory_limit setting, returning the memory limit in KB
 200       *
 201       * @return float
 202       *
 203       * @since 4.1.0
 204       */
 205      private function getMemoryLimit(): float
 206      {
 207          $memoryLimit = ini_get('memory_limit');
 208  
 209          if (preg_match('/^(\d+)(.)$/', $memoryLimit, $matches)) {
 210              if ($matches[2] == 'M') {
 211                  // * nnnM -> nnn MB
 212                  $memoryLimit = $matches[1] * 1024 * 1024;
 213              } else {
 214                  if ($matches[2] == 'K') {
 215                      // * nnnK -> nnn KB
 216                      $memoryLimit = $matches[1] * 1024;
 217                  }
 218              }
 219          }
 220  
 221          return (float) $memoryLimit;
 222      }
 223  }


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer