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\Registry\Registerable;
10 use Org\Mxchange\CoreFramework\Task\Taskable;
11 use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
12 use Org\Mxchange\CoreFramework\Traits\Lists\ListableTrait;
13 use Org\Mxchange\CoreFramework\Traits\Visitor\VisitorTrait;
14 use Org\Mxchange\CoreFramework\Visitor\Visitable;
19 * @author Roland Haeder <webmaster@shipsimu.org>
21 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
22 * @license GNU GPL 3.0 or any newer version
23 * @link http://www.shipsimu.org
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
44 // Exception constants
45 const EXCEPTION_TASK_IS_INVALID = 0xb00;
48 * Protected constructor
52 protected function __construct () {
53 // Call parent constructor
54 parent::__construct(__CLASS__);
57 $this->setHandlerName('task');
61 * Creates an instance of this class
63 * @return $handlerInstance An instance of a HandleableTask class
65 public static final function createTaskHandler () {
67 $handlerInstance = new TaskHandler();
69 // Output debug message
70 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Initializing task handler.');
73 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
75 // Get default instance
76 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
78 // Init visitor instance for faster loop
79 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
81 // Register the first (and generic) idle-loop task
82 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
83 $handlerInstance->registerTask('idle_loop', $taskInstance);
85 // Output debug message
86 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task handler initialized.');
88 // Return the prepared instance
89 return $handlerInstance;
93 * Tries to execute the given task. If as task should not be started (yet)
94 * or the interval time (see task_interval_delay) is not yet reached the
95 * task is quietly skipped.
98 * @throws InvalidTaskException If the current task is invalid
100 private function executeCurrentTask () {
101 // Update no task by default
104 // Is the current task valid?
105 if (!$this->getListInstance()->getIterator()->valid()) {
107 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
111 $currentTask = $this->getListInstance()->getIterator()->current();
113 // Is the task not yet started?
114 if ($currentTask['task_started'] === false) {
115 // Determine difference between current time and registration
116 $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
118 // Should we start now?
119 if ($diff < $currentTask['task_startup_delay']) {
120 // Skip this silently
121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
125 // Launch the task and mark it as updated
126 $currentTask['task_started'] = true;
130 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
133 // Get time difference from interval delay
134 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
137 //* 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']);
139 // Is the interval delay reached?
140 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
141 // Should we update the task from startup?
142 if ($updateTask === true) {
143 // Update the task before leaving
144 $this->updateTask($currentTask);
147 // Skip this silently
152 $currentTask['task_last_activity'] = $this->getMilliTime();
155 $currentTask['task_total_runs']++;
158 $this->updateTask($currentTask);
161 // @TODO Messurement can be added around this call
162 $currentTask['task_instance']->accept($this->getVisitorInstance());
166 * Updates given task by updating the underlaying list
168 * @param $taskEntry An array with a task
171 private function updateTask (array $taskEntry) {
172 // Get the key from current iteration
173 $key = $this->getListInstance()->getIterator()->key();
175 // Get the hash from key
176 $hash = $this->getListInstance()->getHash($key);
179 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
183 * Unregisters the given task
185 * @param $taskData Data of the task
188 private function unregisterTask (array $taskData) {
190 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
193 $this->getListInstance()->removeEntry('tasks', $taskData);
196 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
200 * Searches a task by given instance
202 * @param $taskInstanc An instanceof a Taskable class
203 * @return $taskName Name of the task as used while registration
205 public function searchTask (Taskable $taskInstance) {
206 // Default is an empty (not found) task name
210 $taskList = $this->getListInstance()->getArrayFromList('tasks');
212 // Search all instances
213 foreach ($taskList as $currentTask) {
214 // Does it match given task instance?
215 if ($currentTask['task_instance']->equals($taskInstance)) {
217 $taskName = $currentTask['id'];
229 * Registers a task with a task handler.
231 * @param $taskName A task name to register the task on
232 * @param $taskInstance The instance that should be registered as a task
235 public function registerTask ($taskName, Visitable $taskInstance) {
236 // Get interval delay
237 $intervalDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
238 $startupDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
240 // If the task is 'idle_loop', a deplay of zero seconds is fine
241 assert($intervalDelay >= 0);
242 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
243 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
247 // Identifier for the generateHash() method
249 // Whether the task is started
250 'task_started' => false,
251 // Whether the task is paused (not yet implemented)
252 'task_paused' => false,
253 // Whether the task can be paused (not yet implemented)
254 'task_pauseable' => true,
255 // Timestamp of registration
256 'task_registered' => $this->getMilliTime(),
257 // Last activity timestamp
258 'task_last_activity' => 0,
259 // Total runs of this task
260 'task_total_runs' => 0,
261 // Task instance itself
262 'task_instance' => $taskInstance,
263 // Startup delay in milliseconds
264 'task_startup_delay' => $startupDelay,
265 // Interval time (delay) in milliseconds before this task is executed again
266 'task_interval_delay' => $intervalDelay,
267 // How often should this task run?
268 'task_max_runs' => FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
272 $this->getListInstance()->addEntry('tasks', $taskEntry);
275 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Task registered: taskName=' . $taskName .
276 ' (taskInstance=' . $taskInstance->__toString() . ')' .
277 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
278 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
279 ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
284 * Checks whether tasks are left including idle task
286 * @return $tasksLeft Whether there are tasks left to handle
288 public function hasTasksLeft () {
289 // Do we have tasks there?
290 $tasksLeft = ($this->getListInstance()->count() > 0);
297 * Handles all tasks by checking if they should startup or if it is their
298 * turn to run. You should use this method in a while() loop in conjuntion
299 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
300 * which will attempt to remove all tasks from the task handler.
304 public function handleTasks () {
306 if (!$this->getListInstance()->getIterator()->valid()) {
307 // Rewind to the beginning for next loop
308 $this->getListInstance()->getIterator()->rewind();
311 // Try to execute the task
312 $this->executeCurrentTask();
315 $this->getListInstance()->getIterator()->next();
319 * Shuts down all tasks and the task handler itself. This method should be
320 * called from a corresponding filter class.
324 public function doShutdown () {
325 // Always rewind to the beginning for next loop
326 $this->getListInstance()->getIterator()->rewind();
329 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
331 // Remember all tasks that has been shutdown for removal
334 // Instance a visitor
335 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
337 // Shutdown all tasks in once go
338 while ($this->getListInstance()->getIterator()->valid()) {
340 $currentTask = $this->getListInstance()->getIterator()->current();
342 // Output debug message
343 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
346 $currentTask['task_instance']->accept($this->getVisitorInstance());
348 // Remember this task
349 array_push($tasks, $currentTask);
351 // Advance to next one
352 $this->getListInstance()->getIterator()->next();
356 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER: Shutdown of all tasks completed.');
359 foreach ($tasks as $entry) {
360 $this->unregisterTask($entry);