]> git.mxchange.org Git - core.git/blobdiff - framework/main/classes/handler/tasks/class_TaskHandler.php
Continued:
[core.git] / framework / main / classes / handler / tasks / class_TaskHandler.php
index dfc0142281f1f3ce3a6663f386c0162d8534c6e6..a2aa58d051e085631338d36a2161f7487762cc87 100644 (file)
@@ -3,19 +3,26 @@
 namespace Org\Mxchange\CoreFramework\Handler\Task;
 
 // Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
 use Org\Mxchange\CoreFramework\Handler\BaseHandler;
-use Org\Mxchange\CoreFramework\Lists\Listable;
 use Org\Mxchange\CoreFramework\Registry\Registerable;
 use Org\Mxchange\CoreFramework\Task\Taskable;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
+use Org\Mxchange\CoreFramework\Traits\Lists\ListableTrait;
+use Org\Mxchange\CoreFramework\Traits\Visitor\VisitorTrait;
 use Org\Mxchange\CoreFramework\Visitor\Visitable;
 
+// Import SPL stuff
+use \InvalidArgumentException;
+use \UnexpectedValueException;
+
 /**
  * A Task handler
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.shipsimu.org
  *
@@ -33,6 +40,11 @@ use Org\Mxchange\CoreFramework\Visitor\Visitable;
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
+       // Load traits
+       use IteratorTrait;
+       use ListableTrait;
+       use VisitorTrait;
+
        // Exception constants
        const EXCEPTION_TASK_IS_INVALID = 0xb00;
 
@@ -41,7 +53,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
         *
         * @return      void
         */
-       protected function __construct () {
+       private function __construct () {
                // Call parent constructor
                parent::__construct(__CLASS__);
 
@@ -59,7 +71,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                $handlerInstance = new TaskHandler();
 
                // Output debug message
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Initializing task handler.');
 
                // Init the task list
                $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
@@ -75,7 +87,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                $handlerInstance->registerTask('idle_loop', $taskInstance);
 
                // Output debug message
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task handler initialized.');
 
                // Return the prepared instance
                return $handlerInstance;
@@ -97,7 +109,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                if (!$this->getListInstance()->getIterator()->valid()) {
                        // Not valid!
                        throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
-               } // END - if
+               }
 
                // Get current task
                $currentTask = $this->getListInstance()->getIterator()->current();
@@ -110,35 +122,33 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                        // Should we start now?
                        if ($diff < $currentTask['task_startup_delay']) {
                                // Skip this silently
-                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
                                return;
-                       } // END - if
+                       }
 
                        // Launch the task and mark it as updated
                        $currentTask['task_started'] = true;
                        $updateTask = true;
 
                        // Debug message
-                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
-               } // END - if
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
+               }
 
                // Get time difference from interval delay
                $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
 
-               // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
-
                // Is the interval delay reached?
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
                if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
                        // Should we update the task from startup?
                        if ($updateTask === true) {
                                // Update the task before leaving
                                $this->updateTask($currentTask);
-                       } // END - if
+                       }
 
                        // Skip this silently
                        return;
-               } // END - if
+               }
 
                // Set last activity
                $currentTask['task_last_activity'] = $this->getMilliTime();
@@ -165,7 +175,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                $key = $this->getListInstance()->getIterator()->key();
 
                // Get the hash from key
-               $hash = $this->getListInstance()->getHash($key);
+               $hash = $this->getListInstance()->getHashByIndex($key);
 
                // Update the entry
                $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
@@ -179,13 +189,13 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
         */
        private function unregisterTask (array $taskData) {
                // Debug output
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
 
                // Remove the entry
                $this->getListInstance()->removeEntry('tasks', $taskData);
 
                // Debug output
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
         }
 
        /**
@@ -210,8 +220,8 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
 
                                // Abort here
                                break;
-                       } // END - if
-               } // END - foreach
+                       }
+               }
 
                // Return found name
                return $taskName;
@@ -221,21 +231,43 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
         * Registers a task with a task handler.
         *
         * @param       $taskName               A task name to register the task on
-        * @param       $taskInstance   The instance that should be registered as a task
+        * @param       $taskInstance   An instance of a Taskable class
         * @return      void
+        * @throws      InvalidArgumentException        If a parameter is not valid
+        * @throws      UnexpectedValueException        If an unexpected value has been configured
         */
-       public function registerTask ($taskName, Visitable $taskInstance) {
-               // Get interval delay
-               $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
-               $startupDelay  = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
+       public function registerTask (string $taskName, Taskable $taskInstance) {
+               // Is the parameter valid
+               if (empty($taskName)) {
+                       // Task name cannot be empty
+                       throw new InvalidArgumentException('Parameter "taskName" is empty');
+               }
+
+               // Get interval delay, startup delay and max runs
+               $intervalDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
+               $startupDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
+               $maxRuns = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_max_runs');
 
                // If the task is 'idle_loop', a deplay of zero seconds is fine
-               assert($intervalDelay >= 0);
-               assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
-               assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
+               if ($intervalDelay < 0) {
+                       // Invalid configuration value
+                       throw new UnexpectedValueException(sprintf('taskName=%s has intervalDelay=%d below zero', $taskName, $intervalDelay));
+               } elseif ($startupDelay < 0) {
+                       // Invalid configuration value
+                       throw new UnexpectedValueException(sprintf('taskName=%s has startupDelay=%d below zero', $taskName, $startupDelay));
+               } elseif ($maxRuns < 0) {
+                       // Invalid configuration value
+                       throw new UnexpectedValueException(sprintf('taskName=%s has maxRuns=%d below zero', $taskName, $maxRuns));
+               } elseif ($taskName != 'idle_loop' && $intervalDelay == 0) {
+                       // Only idle_loop can have a zero interval delay
+                       throw new UnexpectedValueException(sprintf('taskName=%s has zero interval delay which is only valid for "idle_loop" task', $taskName));
+               } elseif ($taskName != 'idle_loop' && $startupDelay == 0) {
+                       // Only idle_loop can have a zero interval delay
+                       throw new UnexpectedValueException(sprintf('taskName=%s has zero startup delay which is only valid for "idle_loop" task', $taskName));
+               }
 
                // Create the entry
-               $taskEntry = array(
+               $taskEntry = [
                        // Identifier for the generateHash() method
                        'id'                  => $taskName,
                        // Whether the task is started
@@ -257,14 +289,14 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                        // Interval time (delay) in milliseconds before this task is executed again
                        'task_interval_delay' => $intervalDelay,
                        // How often should this task run?
-                       'task_max_runs'       => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
-               );
+                       'task_max_runs'       => $maxRuns,
+               ];
 
                // Add the entry
                $this->getListInstance()->addEntry('tasks', $taskEntry);
 
                // Debug message
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task registered: taskName=' . $taskName .
                        ' (taskInstance=' . $taskInstance->__toString() . ')' .
                        ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
                        ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
@@ -279,7 +311,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
         */
        public function hasTasksLeft () {
                // Do we have tasks there?
-               $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
+               $tasksLeft = ($this->getListInstance()->count() > 0);
 
                // Return result
                return $tasksLeft;
@@ -298,7 +330,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                if (!$this->getListInstance()->getIterator()->valid()) {
                        // Rewind to the beginning for next loop
                        $this->getListInstance()->getIterator()->rewind();
-               } // END - if
+               }
 
                // Try to execute the task
                $this->executeCurrentTask();
@@ -318,10 +350,10 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                $this->getListInstance()->getIterator()->rewind();
 
                // Debug message
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
 
                // Remember all tasks that has been shutdown for removal
-               $tasks = array();
+               $tasks = [];
 
                // Instance a visitor
                $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
@@ -332,7 +364,7 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
                        $currentTask = $this->getListInstance()->getIterator()->current();
 
                        // Output debug message
-                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
 
                        // Shutdown the task
                        $currentTask['task_instance']->accept($this->getVisitorInstance());
@@ -342,15 +374,15 @@ class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
 
                        // Advance to next one
                        $this->getListInstance()->getIterator()->next();
-               } // END - while
+               }
 
                // Debug message
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutdown of all tasks completed.');
 
                // Remove all tasks
                foreach ($tasks as $entry) {
                        $this->unregisterTask($entry);
-               } // END - foreach
+               }
        }
 
 }