5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
24 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
25 // Exception constants
26 const EXCEPTION_TASK_IS_INVALID = 0xb00;
29 * A task list instance
31 private $listInstance = null;
34 * Instance for iterator
36 private $iteratorInstance = null;
39 * Visitor instance for all tasks while they are active
41 private $visitorInstance = null;
44 * Protected constructor
48 protected function __construct () {
49 // Call parent constructor
50 parent::__construct(__CLASS__);
53 $this->listInstance = ObjectFactory::createObjectByConfiguredName('task_list_class');
55 // Get default instance
56 $this->iteratorInstance = $this->listInstance->getIterator();
58 // Init visitor instance for faster loop
59 $this->visitorInstance = ObjectFactory::createObjectByConfiguredName('active_task_visitor_class');
63 * Creates an instance of this class
65 * @return $handlerInstance An instance of a HandleableTask class
67 public final static function createTaskHandler () {
69 $handlerInstance = new TaskHandler();
71 // Output debug message
72 $handlerInstance->debugOutput('TASK-HANDLER: Task handler initialized.');
74 // Return the prepared instance
75 return $handlerInstance;
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.
84 * @throws InvalidTaskException If the current task is invalid
86 private function executeCurrentTask () {
87 // Update no task by default
90 // Is the current task valid?
91 if (!$this->iteratorInstance->valid()) {
93 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
97 $currentTask = $this->iteratorInstance->current();
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;
104 // Should we start now?
105 if ($diff < $currentTask['task_startup_delay']) {
106 // Skip this silently
110 // Launch the task and mark it as updated
111 $currentTask['task_started'] = true;
115 $this->debugOutput('TASK-HANDLER: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
118 // Get time difference from interval delay
119 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
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);
129 // Skip this silently
134 $currentTask['task_last_activity'] = $this->getMilliTime();
137 $currentTask['task_total_runs']++;
140 $this->updateTask($currentTask);
143 // @TODO Messurement can be added around this call
144 $currentTask['task_instance']->accept($this->visitorInstance);
148 * Updates given task by updating the underlaying list
150 * @param $taskEntry An array with a task
153 private function updateTask (array $taskEntry) {
154 // Get the key from current iteration
155 $key = $this->iteratorInstance->key();
157 // Get the hash from key
158 $hash = $this->listInstance->getHash($key);
161 $this->listInstance->updateCurrentEntryByHash($hash, $taskEntry);
165 * Unregisters the given task
167 * @param $taskName Name of the task
170 private function unregisterTask ($taskName) {
172 $this->listInstance->removeEntry('tasks', $taskName);
176 * Registers a task with a task handler.
178 * @param $taskName A task name to register the task on
179 * @param $taskInstance The instance we should register as a task
182 public function registerTask ($taskName, Visitable $taskInstance) {
185 // Identifier for the generateHash() method
187 // Wether the task is started
188 'task_started' => false,
189 // Wether the task is paused (not yet implemented)
190 'task_paused' => false,
191 // Wether the task can be paused (not yet implemented)
192 'task_pauseable' => true,
193 // Timestamp of registration
194 'task_registered' => $this->getMilliTime(),
195 // Last activity timestamp
196 'task_last_activity' => 0,
197 // Total runs of this task
198 'task_total_runs' => 0,
199 // Task instance itself
200 'task_instance' => $taskInstance,
201 // Startup delay in milliseconds
202 'task_startup_delay' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay'),
203 // Interval time (delay) in milliseconds before this task is executed again
204 'task_interval_delay' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay'),
205 // How often should this task run?
206 'task_max_runs' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
210 $this->listInstance->addEntry('tasks', $taskEntry);
213 $this->debugOutput('TASK-HANDLER: Task ' . $taskName .
214 ' (taskInstance=' . $taskInstance->__toString() . ')' .
215 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
216 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
217 ', maxRuns=' . $taskEntry['task_max_runs'] . ' times registered.'
222 * Checks wether tasks are left including idle task
224 * @return $tasksLeft Wether there are tasks left to handle
226 public function hasTasksLeft () {
227 // Do we have tasks there?
228 $tasksLeft = (($this->listInstance instanceof Listable) && ($this->listInstance->count() > 0));
235 * Handles all tasks by checking if they should startup or if it is their
236 * turn to run. You should use this method in a while() loop in conjuntion
237 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
238 * which will attempt to remove all tasks from the task handler.
242 public function handleTasks () {
244 if (!$this->iteratorInstance->valid()) {
245 // Rewind to the beginning for next loop
246 $this->iteratorInstance->rewind();
249 // Try to execute the task
250 $this->executeCurrentTask();
253 $this->iteratorInstance->next();
257 * Shuts down all tasks and the task handler itself. This method should be
258 * called from a corresponding filter class.
262 public function doShutdown () {
264 if (!$this->iteratorInstance->valid()) {
265 // Rewind to the beginning for next loop
266 $this->iteratorInstance->rewind();
270 $this->debugOutput('TASK-HANDLER: Shutting down all ' . $this->listInstance->count() . ' tasks...');
272 // Remember all tasks that has been shutdown for removal
275 // Shutdown all tasks in once go
276 while ($this->iteratorInstance->valid()) {
278 $current = $this->iteratorInstance->current();
280 // Output debug message
281 $this->debugOutput('TASK-HANDLER: Shutting down task ' . $current['id'] . ' (taskInstance=' . $current['task_instance']->__toString() . ') ...');
284 $current['task_instance']->doShutdown();
286 // Remember this task
289 // Advance to next one
290 $this->iteratorInstance->next();
295 $this->debugOutput('TASK-HANDLER: Shutdown of all tasks completed.');
298 foreach ($tasks as $entry) {
299 $this->unregisterTask($entry);