3 namespace CoreFramework\Handler\Task;
8 * @author Roland Haeder <webmaster@shipsimu.org>
10 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
11 * @license GNU GPL 3.0 or any newer version
12 * @link http://www.shipsimu.org
14 * This program is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27 class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
28 // Exception constants
29 const EXCEPTION_TASK_IS_INVALID = 0xb00;
32 * Protected constructor
36 protected function __construct () {
37 // Call parent constructor
38 parent::__construct(__CLASS__);
41 $this->setHandlerName('task');
45 * Creates an instance of this class
47 * @return $handlerInstance An instance of a HandleableTask class
49 public static final function createTaskHandler () {
51 $handlerInstance = new TaskHandler();
53 // Output debug message
54 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
57 $handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
59 // Get default instance
60 $handlerInstance->setIteratorInstance($handlerInstance->getListInstance()->getIterator());
62 // Init visitor instance for faster loop
63 $handlerInstance->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('active_task_visitor_class'));
65 // Register the first (and generic) idle-loop task
66 $taskInstance = ObjectFactory::createObjectByConfiguredName('idle_task_class');
67 $handlerInstance->registerTask('idle_loop', $taskInstance);
69 // Output debug message
70 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
72 // Return the prepared instance
73 return $handlerInstance;
77 * Tries to execute the given task. If as task should not be started (yet)
78 * or the interval time (see task_interval_delay) is not yet reached the
79 * task is quietly skipped.
82 * @throws InvalidTaskException If the current task is invalid
84 private function executeCurrentTask () {
85 // Update no task by default
88 // Is the current task valid?
89 if (!$this->getListInstance()->getIterator()->valid()) {
91 throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
95 $currentTask = $this->getListInstance()->getIterator()->current();
97 // Is the task not yet started?
98 if ($currentTask['task_started'] === FALSE) {
99 // Determine difference between current time and registration
100 $diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
102 // Should we start now?
103 if ($diff < $currentTask['task_startup_delay']) {
104 // Skip this silently
105 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
109 // Launch the task and mark it as updated
110 $currentTask['task_started'] = TRUE;
114 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
117 // Get time difference from interval delay
118 $diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
121 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
123 // Is the interval delay reached?
124 if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
125 // Should we update the task from startup?
126 if ($updateTask === TRUE) {
127 // Update the task before leaving
128 $this->updateTask($currentTask);
131 // Skip this silently
136 $currentTask['task_last_activity'] = $this->getMilliTime();
139 $currentTask['task_total_runs']++;
142 $this->updateTask($currentTask);
145 // @TODO Messurement can be added around this call
146 $currentTask['task_instance']->accept($this->getVisitorInstance());
150 * Updates given task by updating the underlaying list
152 * @param $taskEntry An array with a task
155 private function updateTask (array $taskEntry) {
156 // Get the key from current iteration
157 $key = $this->getListInstance()->getIterator()->key();
159 // Get the hash from key
160 $hash = $this->getListInstance()->getHash($key);
163 $this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
167 * Unregisters the given task
169 * @param $taskData Data of the task
172 private function unregisterTask (array $taskData) {
174 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
177 $this->getListInstance()->removeEntry('tasks', $taskData);
180 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
184 * Searches a task by given instance
186 * @param $taskInstanc An instanceof a Taskable class
187 * @return $taskName Name of the task as used while registration
189 public function searchTask (Taskable $taskInstance) {
190 // Default is an empty (not found) task name
194 $taskList = $this->getListInstance()->getArrayFromList('tasks');
196 // Search all instances
197 foreach ($taskList as $currentTask) {
198 // Does it match given task instance?
199 if ($currentTask['task_instance']->equals($taskInstance)) {
201 $taskName = $currentTask['id'];
213 * Registers a task with a task handler.
215 * @param $taskName A task name to register the task on
216 * @param $taskInstance The instance we should register as a task
219 public function registerTask ($taskName, Visitable $taskInstance) {
220 // Get interval delay
221 $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
222 $startupDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
224 // If the task is 'idle_loop', a deplay of zero seconds is fine
225 assert($intervalDelay >= 0);
226 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
227 assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
231 // Identifier for the generateHash() method
233 // Whether the task is started
234 'task_started' => FALSE,
235 // Whether the task is paused (not yet implemented)
236 'task_paused' => FALSE,
237 // Whether the task can be paused (not yet implemented)
238 'task_pauseable' => TRUE,
239 // Timestamp of registration
240 'task_registered' => $this->getMilliTime(),
241 // Last activity timestamp
242 'task_last_activity' => 0,
243 // Total runs of this task
244 'task_total_runs' => 0,
245 // Task instance itself
246 'task_instance' => $taskInstance,
247 // Startup delay in milliseconds
248 'task_startup_delay' => $startupDelay,
249 // Interval time (delay) in milliseconds before this task is executed again
250 'task_interval_delay' => $intervalDelay,
251 // How often should this task run?
252 'task_max_runs' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
256 $this->getListInstance()->addEntry('tasks', $taskEntry);
259 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
260 ' (taskInstance=' . $taskInstance->__toString() . ')' .
261 ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
262 ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
263 ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
268 * Checks whether tasks are left including idle task
270 * @return $tasksLeft Whether there are tasks left to handle
272 public function hasTasksLeft () {
273 // Do we have tasks there?
274 $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
281 * Handles all tasks by checking if they should startup or if it is their
282 * turn to run. You should use this method in a while() loop in conjuntion
283 * with hasTasksLeft() so you can e.g. shutdown by adding a ShutdownTask
284 * which will attempt to remove all tasks from the task handler.
288 public function handleTasks () {
290 if (!$this->getListInstance()->getIterator()->valid()) {
291 // Rewind to the beginning for next loop
292 $this->getListInstance()->getIterator()->rewind();
295 // Try to execute the task
296 $this->executeCurrentTask();
299 $this->getListInstance()->getIterator()->next();
303 * Shuts down all tasks and the task handler itself. This method should be
304 * called from a corresponding filter class.
308 public function doShutdown () {
309 // Always rewind to the beginning for next loop
310 $this->getListInstance()->getIterator()->rewind();
313 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
315 // Remember all tasks that has been shutdown for removal
318 // Instance a visitor
319 $this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
321 // Shutdown all tasks in once go
322 while ($this->getListInstance()->getIterator()->valid()) {
324 $currentTask = $this->getListInstance()->getIterator()->current();
326 // Output debug message
327 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
330 $currentTask['task_instance']->accept($this->getVisitorInstance());
332 // Remember this task
333 array_push($tasks, $currentTask);
335 // Advance to next one
336 $this->getListInstance()->getIterator()->next();
340 self::createDebugInstance(__CLASS__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
343 foreach ($tasks as $entry) {
344 $this->unregisterTask($entry);