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