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