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
*
* 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;
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
$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'));
$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;
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();
// 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();
$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);
*/
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!');
}
/**
// Abort here
break;
- } // END - if
- } // END - foreach
+ }
+ }
// Return found name
return $taskName;
* 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
// 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' .
*/
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;
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();
$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'));
$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());
// 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
+ }
}
}