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