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