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