]> git.mxchange.org Git - hub.git/blob - application/hub/main/handler/tasks/class_TaskHandler.php
Added line numbers to debug lines as this will become the 'norm'
[hub.git] / application / hub / main / handler / tasks / class_TaskHandler.php
1 <?php
2 /**
3  * A Task handler
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
25         // Exception constants
26         const EXCEPTION_TASK_IS_INVALID = 0xb00;
27
28         /**
29          * Protected constructor
30          *
31          * @return      void
32          */
33         protected function __construct () {
34                 // Call parent constructor
35                 parent::__construct(__CLASS__);
36
37                 // Set handler name
38                 $this->setHandlerName('task');
39         }
40
41         /**
42          * Creates an instance of this class
43          *
44          * @return      $handlerInstance        An instance of a HandleableTask class
45          */
46         public static final function createTaskHandler () {
47                 // Get new instance
48                 $handlerInstance = new TaskHandler();
49
50                 // Output debug message
51                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Initializing task handler.');
52
53                 // Init the task list
54                 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
55
56                 // Get default instance
57                 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
58
59                 // Init visitor instance for faster loop
60                 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
61
62                 // Register the first (and generic) idle-loop task
63                 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
64                 $handlerInstance->registerTask('idle_loop', $taskInstance);
65
66                 // Output debug message
67                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Task handler initialized.');
68
69                 // Return the prepared instance
70                 return $handlerInstance;
71         }
72
73         /**
74          * Tries to execute the given task. If as task should not be started (yet)
75          * or the interval time (see task_interval_delay) is not yet reached the
76          * task is quietly skipped.
77          *
78          * @return      void
79          * @throws      InvalidTaskException    If the current task is invalid
80          */
81         private function executeCurrentTask () {
82                 // Update no task by default
83                 $updateTask = false;
84
85                 // Is the current task valid?
86                 if (!$this->getListInstance()->getIterator()->valid()) {
87                         // Not valid!
88                         throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
89                 } // END - if
90
91                 // Get current task
92                 $currentTask = $this->getListInstance()->getIterator()->current();
93
94                 // Is the task not yet started?
95                 if ($currentTask['task_started'] === false) {
96                         // Determine difference between current time and registration
97                         $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
98
99                         // Should we start now?
100                         if ($diff < $currentTask['task_startup_delay']) {
101                                 // Skip this silently
102                                 return false;
103                         } // END - if
104
105                         // Launch the task and mark it as updated
106                         $currentTask['task_started'] = true;
107                         $updateTask = true;
108
109                         // Debug message
110                         self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
111                 } // END - if
112
113                 // Get time difference from interval delay
114                 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
115
116                 // Is the interval delay reached?
117                 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_total_runs'] == $currentTask['task_max_runs']) && ($currentTask['task_max_runs'] > 0))) {
118                         // Should we update the task from startup?
119                         if ($updateTask === true) {
120                                 // Update the task before leaving
121                                 $this->updateTask($currentTask);
122                         } // END - if
123
124                         // Skip this silently
125                         return false;
126                 } // END - if
127
128                 // Set last activity
129                 $currentTask['task_last_activity'] = $this->getMilliTime();
130
131                 // Count this run
132                 $currentTask['task_total_runs']++;
133
134                 // Update the task
135                 $this->updateTask($currentTask);
136
137                 // And visit/run it
138                 // @TODO Messurement can be added around this call
139                 $currentTask['task_instance']->accept($this->getVisitorInstance());
140         }
141
142         /**
143          * Updates given task by updating the underlaying list
144          *
145          * @param       $taskEntry      An array with a task
146          * @return      void
147          */
148         private function updateTask (array $taskEntry) {
149                 // Get the key from current iteration
150                 $key = $this->getListInstance()->getIterator()->key();
151
152                 // Get the hash from key
153                 $hash = $this->getListInstance()->getHash($key);
154
155                 // Update the entry
156                 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
157         }
158
159         /**
160          * Unregisters the given task
161          *
162          * @param       $taskData       Data of the task
163          * @return      void
164          */
165         private function unregisterTask (array $taskData) {
166                 // Debug output
167                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - START');
168
169                 // Remove the entry
170                 $this->getListInstance()->removeEntry('tasks', $taskData);
171
172                 // Debug output
173                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - FINISHED');
174          }
175
176         /**
177          * Registers a task with a task handler.
178          *
179          * @param       $taskName               A task name to register the task on
180          * @param       $taskInstance   The instance we should register as a task
181          * @return      void
182          */
183         public function registerTask ($taskName, Visitable $taskInstance) {
184                 // Create the entry
185                 $taskEntry = array(
186                         // Identifier for the generateHash() method
187                         'id'                  => $taskName,
188                         // Whether the task is started
189                         'task_started'        => false,
190                         // Whether the task is paused (not yet implemented)
191                         'task_paused'         => false,
192                         // Whether the task can be paused (not yet implemented)
193                         'task_pauseable'      => true,
194                         // Timestamp of registration
195                         'task_registered'     => $this->getMilliTime(),
196                         // Last activity timestamp
197                         'task_last_activity'  => 0,
198                         // Total runs of this task
199                         'task_total_runs'     => 0,
200                         // Task instance itself
201                         'task_instance'       => $taskInstance,
202                         // Startup delay in milliseconds
203                         'task_startup_delay'  => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay'),
204                         // Interval time (delay) in milliseconds before this task is executed again
205                         'task_interval_delay' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay'),
206                         // How often should this task run?
207                         'task_max_runs'       => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
208                 );
209
210                 // Add the entry
211                 $this->getListInstance()->addEntry('tasks', $taskEntry);
212
213                 // Debug message
214                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Task registered: taskName=' . $taskName .
215                         ' (taskInstance=' . $taskInstance->__toString() . ')' .
216                         ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
217                         ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
218                         ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
219                 );
220         }
221
222         /**
223          * Checks whether tasks are left including idle task
224          *
225          * @return      $tasksLeft      Whether there are tasks left to handle
226          */
227         public function hasTasksLeft () {
228                 // Do we have tasks there?
229                 $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
230
231                 // Return result
232                 return $tasksLeft;
233         }
234
235         /**
236          * Handles all tasks by checking if they should startup or if it is their
237          * turn to run. You should use this method in a while() loop in conjuntion
238          * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
239          * which will attempt to remove all tasks from the task handler.
240          *
241          * @return      void
242          */
243         public function handleTasks () {
244                 // Should we rewind?
245                 if (!$this->getListInstance()->getIterator()->valid()) {
246                         // Rewind to the beginning for next loop
247                         $this->getListInstance()->getIterator()->rewind();
248                 } // END - if
249
250                 // Try to execute the task
251                 $this->executeCurrentTask();
252
253                 // Go to next entry
254                 $this->getListInstance()->getIterator()->next();
255         }
256
257         /**
258          * Shuts down all tasks and the task handler itself. This method should be
259          * called from a corresponding filter class.
260          * 
261          * @return      void
262          */
263         public function doShutdown () {
264                 // Always rewind to the beginning for next loop
265                 $this->getListInstance()->getIterator()->rewind();
266
267                 // Debug message
268                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
269
270                 // Remember all tasks that has been shutdown for removal
271                 $tasks = array();
272
273                 // Instance a visitor
274                 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
275
276                 // Shutdown all tasks in once go
277                 while ($this->getListInstance()->getIterator()->valid()) {
278                         // Get current entry
279                         $currentTask = $this->getListInstance()->getIterator()->current();
280
281                         // Output debug message
282                         self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
283
284                         // Shutdown the task
285                         $currentTask['task_instance']->accept($this->getVisitorInstance());
286
287                         // Remember this task
288                         $tasks[] = $currentTask;
289
290                         // Advance to next one
291                         $this->getListInstance()->getIterator()->next();
292                 } // END - while
293
294                 // Debug message
295                 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __LINE__ . ']: Shutdown of all tasks completed.');
296
297                 // Remove all tasks
298                 foreach ($tasks as $entry) {
299                         $this->unregisterTask($entry);
300                 } // END - foreach
301         }
302 }
303
304 // [EOF]
305 ?>