3 namespace Org\Mxchange\CoreFramework\Handler\Task;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7 use Org\Mxchange\CoreFramework\Handler\BaseHandler;
8 use Org\Mxchange\CoreFramework\Lists\Listable;
9 use Org\Mxchange\CoreFramework\Registry\Registerable;
10 use Org\Mxchange\CoreFramework\Task\Taskable;
11 use Org\Mxchange\CoreFramework\Visitor\Visitable;
16 * @author Roland Haeder <webmaster@shipsimu.org>
18 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
19 * @license GNU GPL 3.0 or any newer version
20 * @link http://www.shipsimu.org
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
36 // Exception constants
37 const EXCEPTION_TASK_IS_INVALID = 0xb00;
40 * Protected constructor
44 protected function __construct () {
45 // Call parent constructor
46 parent::__construct(__CLASS__);
49 $this->setHandlerName('task');
53 * Creates an instance of this class
55 * @return $handlerInstance An instance of a HandleableTask class
57 public static final function createTaskHandler () {
59 $handlerInstance = new TaskHandler();
61 // Output debug message
62 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
65 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
67 // Get default instance
68 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
70 // Init visitor instance for faster loop
71 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
73 // Register the first (and generic) idle-loop task
74 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
75 $handlerInstance->registerTask('idle_loop', $taskInstance);
77 // Output debug message
78 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
80 // Return the prepared instance
81 return $handlerInstance;
85 * Tries to execute the given task. If as task should not be started (yet)
86 * or the interval time (see task_interval_delay) is not yet reached the
87 * task is quietly skipped.
90 * @throws InvalidTaskException If the current task is invalid
92 private function executeCurrentTask () {
93 // Update no task by default
96 // Is the current task valid?
97 if (!$this->getListInstance()->getIterator()->valid()) {
99 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
103 $currentTask = $this->getListInstance()->getIterator()->current();
105 // Is the task not yet started?
106 if ($currentTask['task_started'] === false) {
107 // Determine difference between current time and registration
108 $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
110 // Should we start now?
111 if ($diff < $currentTask['task_startup_delay']) {
112 // Skip this silently
113 //* 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']);
117 // Launch the task and mark it as updated
118 $currentTask['task_started'] = true;
122 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
125 // Get time difference from interval delay
126 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
129 //* 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']);
131 // Is the interval delay reached?
132 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
133 // Should we update the task from startup?
134 if ($updateTask === true) {
135 // Update the task before leaving
136 $this->updateTask($currentTask);
139 // Skip this silently
144 $currentTask['task_last_activity'] = $this->getMilliTime();
147 $currentTask['task_total_runs']++;
150 $this->updateTask($currentTask);
153 // @TODO Messurement can be added around this call
154 $currentTask['task_instance']->accept($this->getVisitorInstance());
158 * Updates given task by updating the underlaying list
160 * @param $taskEntry An array with a task
163 private function updateTask (array $taskEntry) {
164 // Get the key from current iteration
165 $key = $this->getListInstance()->getIterator()->key();
167 // Get the hash from key
168 $hash = $this->getListInstance()->getHash($key);
171 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
175 * Unregisters the given task
177 * @param $taskData Data of the task
180 private function unregisterTask (array $taskData) {
182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
185 $this->getListInstance()->removeEntry('tasks', $taskData);
188 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
192 * Searches a task by given instance
194 * @param $taskInstanc An instanceof a Taskable class
195 * @return $taskName Name of the task as used while registration
197 public function searchTask (Taskable $taskInstance) {
198 // Default is an empty (not found) task name
202 $taskList = $this->getListInstance()->getArrayFromList('tasks');
204 // Search all instances
205 foreach ($taskList as $currentTask) {
206 // Does it match given task instance?
207 if ($currentTask['task_instance']->equals($taskInstance)) {
209 $taskName = $currentTask['id'];
221 * Registers a task with a task handler.
223 * @param $taskName A task name to register the task on
224 * @param $taskInstance The instance that should be registered as a task
227 public function registerTask ($taskName, Visitable $taskInstance) {
228 // Get interval delay
229 $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
230 $startupDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
232 // If the task is 'idle_loop', a deplay of zero seconds is fine
233 assert($intervalDelay >= 0);
234 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
235 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
239 // Identifier for the generateHash() method
241 // Whether the task is started
242 'task_started' => false,
243 // Whether the task is paused (not yet implemented)
244 'task_paused' => false,
245 // Whether the task can be paused (not yet implemented)
246 'task_pauseable' => true,
247 // Timestamp of registration
248 'task_registered' => $this->getMilliTime(),
249 // Last activity timestamp
250 'task_last_activity' => 0,
251 // Total runs of this task
252 'task_total_runs' => 0,
253 // Task instance itself
254 'task_instance' => $taskInstance,
255 // Startup delay in milliseconds
256 'task_startup_delay' => $startupDelay,
257 // Interval time (delay) in milliseconds before this task is executed again
258 'task_interval_delay' => $intervalDelay,
259 // How often should this task run?
260 'task_max_runs' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
264 $this->getListInstance()->addEntry('tasks', $taskEntry);
267 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
268 ' (taskInstance=' . $taskInstance->__toString() . ')' .
269 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
270 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
271 ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
276 * Checks whether tasks are left including idle task
278 * @return $tasksLeft Whether there are tasks left to handle
280 public function hasTasksLeft () {
281 // Do we have tasks there?
282 $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
289 * Handles all tasks by checking if they should startup or if it is their
290 * turn to run. You should use this method in a while() loop in conjuntion
291 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
292 * which will attempt to remove all tasks from the task handler.
296 public function handleTasks () {
298 if (!$this->getListInstance()->getIterator()->valid()) {
299 // Rewind to the beginning for next loop
300 $this->getListInstance()->getIterator()->rewind();
303 // Try to execute the task
304 $this->executeCurrentTask();
307 $this->getListInstance()->getIterator()->next();
311 * Shuts down all tasks and the task handler itself. This method should be
312 * called from a corresponding filter class.
316 public function doShutdown () {
317 // Always rewind to the beginning for next loop
318 $this->getListInstance()->getIterator()->rewind();
321 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
323 // Remember all tasks that has been shutdown for removal
326 // Instance a visitor
327 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
329 // Shutdown all tasks in once go
330 while ($this->getListInstance()->getIterator()->valid()) {
332 $currentTask = $this->getListInstance()->getIterator()->current();
334 // Output debug message
335 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
338 $currentTask['task_instance']->accept($this->getVisitorInstance());
340 // Remember this task
341 array_push($tasks, $currentTask);
343 // Advance to next one
344 $this->getListInstance()->getIterator()->next();
348 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
351 foreach ($tasks as $entry) {
352 $this->unregisterTask($entry);