3 namespace CoreFramework\Handler\Task;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Registry\Registerable;
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
32 // Exception constants
33 const EXCEPTION_TASK_IS_INVALID = 0xb00;
36 * Protected constructor
40 protected function __construct () {
41 // Call parent constructor
42 parent::__construct(__CLASS__);
45 $this->setHandlerName('task');
49 * Creates an instance of this class
51 * @return $handlerInstance An instance of a HandleableTask class
53 public static final function createTaskHandler () {
55 $handlerInstance = new TaskHandler();
57 // Output debug message
58 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
61 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
63 // Get default instance
64 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
66 // Init visitor instance for faster loop
67 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
69 // Register the first (and generic) idle-loop task
70 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
71 $handlerInstance->registerTask('idle_loop', $taskInstance);
73 // Output debug message
74 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
76 // Return the prepared instance
77 return $handlerInstance;
81 * Tries to execute the given task. If as task should not be started (yet)
82 * or the interval time (see task_interval_delay) is not yet reached the
83 * task is quietly skipped.
86 * @throws InvalidTaskException If the current task is invalid
88 private function executeCurrentTask () {
89 // Update no task by default
92 // Is the current task valid?
93 if (!$this->getListInstance()->getIterator()->valid()) {
95 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
99 $currentTask = $this->getListInstance()->getIterator()->current();
101 // Is the task not yet started?
102 if ($currentTask['task_started'] === FALSE) {
103 // Determine difference between current time and registration
104 $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
106 // Should we start now?
107 if ($diff < $currentTask['task_startup_delay']) {
108 // Skip this silently
109 //* 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']);
113 // Launch the task and mark it as updated
114 $currentTask['task_started'] = TRUE;
118 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
121 // Get time difference from interval delay
122 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
125 //* 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']);
127 // Is the interval delay reached?
128 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
129 // Should we update the task from startup?
130 if ($updateTask === TRUE) {
131 // Update the task before leaving
132 $this->updateTask($currentTask);
135 // Skip this silently
140 $currentTask['task_last_activity'] = $this->getMilliTime();
143 $currentTask['task_total_runs']++;
146 $this->updateTask($currentTask);
149 // @TODO Messurement can be added around this call
150 $currentTask['task_instance']->accept($this->getVisitorInstance());
154 * Updates given task by updating the underlaying list
156 * @param $taskEntry An array with a task
159 private function updateTask (array $taskEntry) {
160 // Get the key from current iteration
161 $key = $this->getListInstance()->getIterator()->key();
163 // Get the hash from key
164 $hash = $this->getListInstance()->getHash($key);
167 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
171 * Unregisters the given task
173 * @param $taskData Data of the task
176 private function unregisterTask (array $taskData) {
178 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
181 $this->getListInstance()->removeEntry('tasks', $taskData);
184 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
188 * Searches a task by given instance
190 * @param $taskInstanc An instanceof a Taskable class
191 * @return $taskName Name of the task as used while registration
193 public function searchTask (Taskable $taskInstance) {
194 // Default is an empty (not found) task name
198 $taskList = $this->getListInstance()->getArrayFromList('tasks');
200 // Search all instances
201 foreach ($taskList as $currentTask) {
202 // Does it match given task instance?
203 if ($currentTask['task_instance']->equals($taskInstance)) {
205 $taskName = $currentTask['id'];
217 * Registers a task with a task handler.
219 * @param $taskName A task name to register the task on
220 * @param $taskInstance The instance we should register as a task
223 public function registerTask ($taskName, Visitable $taskInstance) {
224 // Get interval delay
225 $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
226 $startupDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
228 // If the task is 'idle_loop', a deplay of zero seconds is fine
229 assert($intervalDelay >= 0);
230 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
231 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
235 // Identifier for the generateHash() method
237 // Whether the task is started
238 'task_started' => FALSE,
239 // Whether the task is paused (not yet implemented)
240 'task_paused' => FALSE,
241 // Whether the task can be paused (not yet implemented)
242 'task_pauseable' => TRUE,
243 // Timestamp of registration
244 'task_registered' => $this->getMilliTime(),
245 // Last activity timestamp
246 'task_last_activity' => 0,
247 // Total runs of this task
248 'task_total_runs' => 0,
249 // Task instance itself
250 'task_instance' => $taskInstance,
251 // Startup delay in milliseconds
252 'task_startup_delay' => $startupDelay,
253 // Interval time (delay) in milliseconds before this task is executed again
254 'task_interval_delay' => $intervalDelay,
255 // How often should this task run?
256 'task_max_runs' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
260 $this->getListInstance()->addEntry('tasks', $taskEntry);
263 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
264 ' (taskInstance=' . $taskInstance->__toString() . ')' .
265 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
266 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
267 ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
272 * Checks whether tasks are left including idle task
274 * @return $tasksLeft Whether there are tasks left to handle
276 public function hasTasksLeft () {
277 // Do we have tasks there?
278 $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
285 * Handles all tasks by checking if they should startup or if it is their
286 * turn to run. You should use this method in a while() loop in conjuntion
287 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
288 * which will attempt to remove all tasks from the task handler.
292 public function handleTasks () {
294 if (!$this->getListInstance()->getIterator()->valid()) {
295 // Rewind to the beginning for next loop
296 $this->getListInstance()->getIterator()->rewind();
299 // Try to execute the task
300 $this->executeCurrentTask();
303 $this->getListInstance()->getIterator()->next();
307 * Shuts down all tasks and the task handler itself. This method should be
308 * called from a corresponding filter class.
312 public function doShutdown () {
313 // Always rewind to the beginning for next loop
314 $this->getListInstance()->getIterator()->rewind();
317 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
319 // Remember all tasks that has been shutdown for removal
322 // Instance a visitor
323 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
325 // Shutdown all tasks in once go
326 while ($this->getListInstance()->getIterator()->valid()) {
328 $currentTask = $this->getListInstance()->getIterator()->current();
330 // Output debug message
331 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
334 $currentTask['task_instance']->accept($this->getVisitorInstance());
336 // Remember this task
337 array_push($tasks, $currentTask);
339 // Advance to next one
340 $this->getListInstance()->getIterator()->next();
344 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
347 foreach ($tasks as $entry) {
348 $this->unregisterTask($entry);