3 namespace Org\Mxchange\CoreFramework\Handler\Task;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Handler\BaseHandler;
9 use Org\Mxchange\CoreFramework\Lists\Listable;
10 use Org\Mxchange\CoreFramework\Registry\Registerable;
11 use Org\Mxchange\CoreFramework\Task\Taskable;
12 use Org\Mxchange\CoreFramework\Visitor\Visitable;
13 use Org\Mxchange\CoreFramework\Visitor\Visitor;
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
38 // Exception constants
39 const EXCEPTION_TASK_IS_INVALID = 0xb00;
42 * Visitor handler instance
44 private $visitorInstance = NULL;
47 * Instance of the list
49 private $listInstance = NULL;
52 * Protected constructor
56 protected function __construct () {
57 // Call parent constructor
58 parent::__construct(__CLASS__);
61 $this->setHandlerName('task');
65 * Creates an instance of this class
67 * @return $handlerInstance An instance of a HandleableTask class
69 public static final function createTaskHandler () {
71 $handlerInstance = new TaskHandler();
73 // Output debug message
74 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Initializing task handler.');
77 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
79 // Get default instance
80 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
82 // Init visitor instance for faster loop
83 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
85 // Register the first (and generic) idle-loop task
86 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
87 $handlerInstance->registerTask('idle_loop', $taskInstance);
89 // Output debug message
90 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task handler initialized.');
92 // Return the prepared instance
93 return $handlerInstance;
97 * Setter for visitor instance
99 * @param $visitorInstance An instance of a Visitor class
102 protected final function setVisitorInstance (Visitor $visitorInstance) {
103 $this->visitorInstance = $visitorInstance;
107 * Getter for visitor instance
109 * @return $visitorInstance An instance of a Visitor class
111 protected final function getVisitorInstance () {
112 return $this->visitorInstance;
116 * Setter for the list instance
118 * @param $listInstance A list of Listable
121 protected final function setListInstance (Listable $listInstance) {
122 $this->listInstance = $listInstance;
126 * Getter for the list instance
128 * @return $listInstance A list of Listable
130 protected final function getListInstance () {
131 return $this->listInstance;
135 * Tries to execute the given task. If as task should not be started (yet)
136 * or the interval time (see task_interval_delay) is not yet reached the
137 * task is quietly skipped.
140 * @throws InvalidTaskException If the current task is invalid
142 private function executeCurrentTask () {
143 // Update no task by default
146 // Is the current task valid?
147 if (!$this->getListInstance()->getIterator()->valid()) {
149 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
153 $currentTask = $this->getListInstance()->getIterator()->current();
155 // Is the task not yet started?
156 if ($currentTask['task_started'] === false) {
157 // Determine difference between current time and registration
158 $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
160 // Should we start now?
161 if ($diff < $currentTask['task_startup_delay']) {
162 // Skip this silently
163 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
167 // Launch the task and mark it as updated
168 $currentTask['task_started'] = true;
172 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
175 // Get time difference from interval delay
176 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
179 //* 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']);
181 // Is the interval delay reached?
182 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
183 // Should we update the task from startup?
184 if ($updateTask === true) {
185 // Update the task before leaving
186 $this->updateTask($currentTask);
189 // Skip this silently
194 $currentTask['task_last_activity'] = $this->getMilliTime();
197 $currentTask['task_total_runs']++;
200 $this->updateTask($currentTask);
203 // @TODO Messurement can be added around this call
204 $currentTask['task_instance']->accept($this->getVisitorInstance());
208 * Updates given task by updating the underlaying list
210 * @param $taskEntry An array with a task
213 private function updateTask (array $taskEntry) {
214 // Get the key from current iteration
215 $key = $this->getListInstance()->getIterator()->key();
217 // Get the hash from key
218 $hash = $this->getListInstance()->getHash($key);
221 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
225 * Unregisters the given task
227 * @param $taskData Data of the task
230 private function unregisterTask (array $taskData) {
232 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
235 $this->getListInstance()->removeEntry('tasks', $taskData);
238 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
242 * Searches a task by given instance
244 * @param $taskInstanc An instanceof a Taskable class
245 * @return $taskName Name of the task as used while registration
247 public function searchTask (Taskable $taskInstance) {
248 // Default is an empty (not found) task name
252 $taskList = $this->getListInstance()->getArrayFromList('tasks');
254 // Search all instances
255 foreach ($taskList as $currentTask) {
256 // Does it match given task instance?
257 if ($currentTask['task_instance']->equals($taskInstance)) {
259 $taskName = $currentTask['id'];
271 * Registers a task with a task handler.
273 * @param $taskName A task name to register the task on
274 * @param $taskInstance The instance that should be registered as a task
277 public function registerTask ($taskName, Visitable $taskInstance) {
278 // Get interval delay
279 $intervalDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
280 $startupDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
282 // If the task is 'idle_loop', a deplay of zero seconds is fine
283 assert($intervalDelay >= 0);
284 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
285 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
289 // Identifier for the generateHash() method
291 // Whether the task is started
292 'task_started' => false,
293 // Whether the task is paused (not yet implemented)
294 'task_paused' => false,
295 // Whether the task can be paused (not yet implemented)
296 'task_pauseable' => true,
297 // Timestamp of registration
298 'task_registered' => $this->getMilliTime(),
299 // Last activity timestamp
300 'task_last_activity' => 0,
301 // Total runs of this task
302 'task_total_runs' => 0,
303 // Task instance itself
304 'task_instance' => $taskInstance,
305 // Startup delay in milliseconds
306 'task_startup_delay' => $startupDelay,
307 // Interval time (delay) in milliseconds before this task is executed again
308 'task_interval_delay' => $intervalDelay,
309 // How often should this task run?
310 'task_max_runs' => FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
314 $this->getListInstance()->addEntry('tasks', $taskEntry);
317 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task registered: taskName=' . $taskName .
318 ' (taskInstance=' . $taskInstance->__toString() . ')' .
319 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
320 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
321 ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
326 * Checks whether tasks are left including idle task
328 * @return $tasksLeft Whether there are tasks left to handle
330 public function hasTasksLeft () {
331 // Do we have tasks there?
332 $tasksLeft = ($this->getListInstance()->count() > 0);
339 * Handles all tasks by checking if they should startup or if it is their
340 * turn to run. You should use this method in a while() loop in conjuntion
341 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
342 * which will attempt to remove all tasks from the task handler.
346 public function handleTasks () {
348 if (!$this->getListInstance()->getIterator()->valid()) {
349 // Rewind to the beginning for next loop
350 $this->getListInstance()->getIterator()->rewind();
353 // Try to execute the task
354 $this->executeCurrentTask();
357 $this->getListInstance()->getIterator()->next();
361 * Shuts down all tasks and the task handler itself. This method should be
362 * called from a corresponding filter class.
366 public function doShutdown () {
367 // Always rewind to the beginning for next loop
368 $this->getListInstance()->getIterator()->rewind();
371 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
373 // Remember all tasks that has been shutdown for removal
376 // Instance a visitor
377 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
379 // Shutdown all tasks in once go
380 while ($this->getListInstance()->getIterator()->valid()) {
382 $currentTask = $this->getListInstance()->getIterator()->current();
384 // Output debug message
385 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
388 $currentTask['task_instance']->accept($this->getVisitorInstance());
390 // Remember this task
391 array_push($tasks, $currentTask);
393 // Advance to next one
394 $this->getListInstance()->getIterator()->next();
398 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutdown of all tasks completed.');
401 foreach ($tasks as $entry) {
402 $this->unregisterTask($entry);