d603d6ee8f6a5fddcc4936e185ac29b1af933296
[Packages/TYPO3.CMS.git] / typo3 / sysext / scheduler / class.tx_scheduler.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2005 Christian Jul Jensen <julle@typo3.org>
6 *
7 * All rights reserved
8 *
9 * This script is part of the TYPO3 project. The TYPO3 project is
10 * free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * The GNU General Public License can be found at
16 * http://www.gnu.org/copyleft/gpl.html.
17 *
18 * This script is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * This copyright notice MUST APPEAR in all copies of the script!
24 ***************************************************************/
25 /**
26 * TYPO3 Scheduler. This class handles scheduling and execution of tasks.
27 * Formerly known as "Gabriel TYPO3 arch angel"
28 *
29 * @author Francois Suter <francois@typo3.org>
30 * @author Christian Jul Jensen <julle@typo3.org>
31 *
32 * @package TYPO3
33 * @subpackage tx_scheduler
34 *
35 * $Id: class.tx_scheduler.php 1198 2009-09-06 21:11:11Z francois $
36 */
37
38 class tx_scheduler implements t3lib_Singleton {
39 /**
40 * @var array $extConf: settings from the extension manager
41 */
42 var $extConf = array();
43
44 /**
45 * Constructor, makes sure all derived client classes are included
46 *
47 * @return void
48 */
49 public function __construct() {
50 // Get configuration from the extension manager
51 $this->extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['scheduler']);
52 if (empty($this->extConf['maxLifetime'])) {
53 $this->extConf['maxLifetime'] = 1440;
54 }
55
56 // Clean up the serialized execution arrays
57 $this->cleanExecutionArrays();
58 }
59
60 /**
61 * Adds a task to the pool
62 *
63 * @param tx_scheduler_Task $task: the object representing the task to add
64 * @param string $identifier: the identified of the task
65 * @return boolean True if the task was successfully added, false otherwise
66 */
67 public function addTask(tx_scheduler_Task $task) {
68 $taskUid = $task->getTaskUid();
69 if (empty($taskUid)) {
70 $fields = array(
71 'crdate' => $GLOBALS['EXEC_TIME'],
72 'classname' => get_class($task),
73 'disable' => $task->isDisabled(),
74 'serialized_task_object' => 'RESERVED'
75 );
76 $result = $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_scheduler_task', $fields);
77 if ($result) {
78 $task->setTaskUid($GLOBALS['TYPO3_DB']->sql_insert_id());
79 $task->save();
80 $result = true;
81 } else {
82 $result = false;
83 }
84 } else {
85 $result = false;
86 }
87 return $result;
88 }
89
90 /**
91 * Cleans the execution lists of the scheduled tasks, executions older than 24h are removed
92 * TODO: find a way to actually kill the job
93 *
94 * @return void
95 */
96 protected function cleanExecutionArrays() {
97 $tstamp = $GLOBALS['EXEC_TIME'];
98
99 // Select all tasks with executions
100 // NOTE: this cleanup is done for disabled tasks too,
101 // to avoid leaving old executions lying around
102 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
103 'uid, classname, serialized_executions',
104 'tx_scheduler_task',
105 'serialized_executions != \'\''
106 );
107
108 $maxDuration = $this->extConf['maxLifetime'] * 60;
109 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
110 if (($serialized_executions = unserialize($row['serialized_executions']))) {
111 $executions = array();
112 foreach ($serialized_executions AS $task) {
113 if (($tstamp - $task) < $maxDuration) {
114 $executions[] = $task;
115 } else {
116 $GLOBALS['BE_USER']->writelog(
117 4,
118 0,
119 0,
120 'scheduler',
121 '[scheduler]: Removing logged execution, assuming that the process is dead. Execution of \'' . $row['classname'] . '\' (UID: ' . $row['uid']. ') was started at '.date('Y-m-d H:i:s', $task),
122 array()
123 );
124 }
125 }
126 }
127
128 if (count($serialized_executions) != count($executions)) {
129 if (count($executions) == 0) {
130 $value = '';
131 } else {
132 $value = serialize($executions);
133 }
134
135 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
136 'tx_scheduler_task',
137 'uid = ' . intval($row['uid']),
138 array('serialized_executions' => $value)
139 );
140 }
141 }
142 $GLOBALS['TYPO3_DB']->sql_free_result($res);
143 }
144
145 /**
146 * This method executes the given task and properly marks and records that execution
147 * It is expected to return false if the task was barred from running or if it was not saved properly
148 *
149 * @param tx_scheduler_Task $task: the task to execute
150 * @return boolean Whether the task was saved succesfully to the database or not
151 */
152 public function executeTask(tx_scheduler_Task $task) {
153
154 // Task is already running and multiple executions are not allowed
155 if (!$task->areMultipleExecutionsAllowed() && $task->isExecutionRunning()) {
156 // Log multiple execution error
157 $GLOBALS['BE_USER']->writelog(
158 4,
159 0,
160 0,
161 'scheduler',
162 '[scheduler]: Task is already running and multiple executions are not allowed, skipping! Class: ' . get_class($task) . ', UID: ' . $task->getTaskUid(),
163 array()
164 );
165
166 $result = false;
167
168 // Task isn't running or multiple executions are allowed
169 } else {
170 // Log scheduler invocation
171 $GLOBALS['BE_USER']->writelog(
172 4,
173 0,
174 0,
175 'scheduler',
176 '[scheduler]: Start execution. Class: ' . get_class($task) . ', UID: ' . $task->getTaskUid(),
177 array()
178 );
179
180 // Register execution
181 $executionID = $task->markExecution();
182
183 $failure = null;
184 try {
185 // Execute task
186 $successfullyExecuted = $task->execute();
187
188 if (!$successfullyExecuted) {
189 throw new tx_scheduler_FailedExecutionException(
190 'Task failed to execute successfully. Class: ' . get_class($task) . ', UID: ' . $task->getTaskUid(),
191 1250596541
192 );
193 }
194 } catch(Exception $e) {
195 // Store exception, so that it can be saved to database
196 $failure = $e;
197 }
198
199 // Unregister excution
200 $task->unmarkExecution($executionID, $failure);
201
202 // Log completion of execution
203 $GLOBALS['BE_USER']->writelog(
204 4,
205 0,
206 0,
207 'scheduler',
208 '[scheduler]: Task executed. Class: ' . get_class($task). ', UID: ' . $task->getTaskUid(),
209 array()
210 );
211 $result = $task->save();
212
213 // Now that the result of the task execution has been handled,
214 // throw the exception again, if any
215 if ($failure instanceof Exception) {
216 throw $failure;
217 }
218 }
219
220 return $result;
221 }
222
223 /**
224 * This method stores information about the last run of the Scheduler into the system registry
225 *
226 * @param string $type: Type of run (manual or command-line (assumed to be cron))
227 * @return void
228 */
229 public function recordLastRun($type = 'cron') {
230 // Validate input value
231 if ($type != 'manual') {
232 $type = 'cron';
233 }
234
235 /**
236 * @var t3lib_Registry
237 */
238 $registry = t3lib_div::makeInstance('t3lib_Registry');
239 $runInformation = array('start' => $GLOBALS['EXEC_TIME'], 'end' => time(), 'type' => $type);
240 $registry->set('tx_scheduler', 'lastRun', $runInformation);
241 }
242
243 /**
244 * Removes a task completely from the system.
245 * TODO: find a way to actually kill the existing jobs
246 *
247 * @param tx_scheduler_Task $task: the object representing the task to delete
248 * @return boolean True if task was successfully deleted, false otherwise
249 */
250 public function removeTask(tx_scheduler_Task $task) {
251 $taskUid = $task->getTaskUid();
252 if (!empty($taskUid)) {
253 return $GLOBALS['TYPO3_DB']->exec_DELETEquery('tx_scheduler_task', 'uid = ' . $taskUid);
254 } else {
255 return false;
256 }
257 }
258
259 /**
260 * Updates a task in the pool
261 *
262 * @param tx_scheduler_Task $task: Scheduler task object
263 * @return boolean False if submitted task was not of proper class
264 */
265 public function saveTask(tx_scheduler_Task $task) {
266 $taskUid = $task->getTaskUid();
267 if (!empty($taskUid)) {
268 try {
269 $executionTime = $task->getNextDueExecution();
270 $task->setExecutionTime($executionTime);
271 }
272 catch (Exception $e) {
273 $task->setDisabled(true);
274 $executionTime = 0;
275 }
276 $task->unsetScheduler();
277 $fields = array(
278 'nextexecution' => $executionTime,
279 'classname' => get_class($task),
280 'disable' => $task->isDisabled(),
281 'serialized_task_object' => serialize($task)
282 );
283 return $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', "uid = '" . $taskUid . "'", $fields);
284 } else {
285 return false;
286 }
287 }
288
289 /**
290 * Fetches and unserializes a task object from the db. If an uid is given the object
291 * with the uid is returned, else the object representing the next due task is returned.
292 * If there are no due tasks the method throws an exception.
293 *
294 * @param integer $uid: primary key of a task
295 * @return tx_scheduler_Task The fetched task object
296 */
297 public function fetchTask($uid = 0) {
298 // Define where clause
299 // If no uid is given, take any non-disabled task which has a next execution time in the past
300 if (empty($uid)) {
301 $whereClause = 'disable = 0 AND nextexecution != 0 AND nextexecution <= ' . $GLOBALS['EXEC_TIME'];
302 } else {
303 $whereClause = 'uid = ' . intval($uid);
304 }
305
306 $queryArray = array(
307 'SELECT' => 'serialized_task_object',
308 'FROM' => 'tx_scheduler_task',
309 'WHERE' => $whereClause,
310 'LIMIT' => 1
311 );
312 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryArray);
313
314 // If there are no available tasks, thrown an exception
315 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
316 throw new OutOfBoundsException('No task', 1247827244);
317
318 // Otherwise unserialize the task and return it
319 } else {
320 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
321 $task = unserialize($row['serialized_task_object']);
322 $task->setScheduler();
323 $GLOBALS['TYPO3_DB']->sql_free_result($res);
324 return $task;
325 }
326 }
327
328 /**
329 * This method is used to get the database record for a given task
330 * It returns the database record and not the task object
331 *
332 * @param integer $uid: primary key of the task to get
333 * @return array Database record for the task
334 * @see tx_scheduler::fetchTask()
335 */
336 public function fetchTaskRecord($uid) {
337 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_scheduler_task', "uid = '" . intval($uid) . "'");
338
339 // If the task is not found, throw an exception
340 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
341 throw new OutOfBoundsException('No task', 1247827244);
342
343 // Otherwise get the task's record
344 } else {
345 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
346 $GLOBALS['TYPO3_DB']->sql_free_result($res);
347 }
348 return $row;
349 }
350
351 /**
352 * Fetches and unserializes task objects selected with some (SQL) condition
353 * Objects are returned as an array
354 *
355 * @param string $where: part of a SQL where clause (without the "WHERE" keyword)
356 * @param boolean $includeDisabledTasks: true if disabled tasks should be fetched too, false otherwise
357 * @return array List of task objects
358 */
359 public function fetchTasksWithCondition($where, $includeDisabledTasks = false) {
360 $tasks = array();
361 if (!empty($where)) {
362 $whereClause = $where;
363 }
364 if (!$includeDisabledTasks) {
365 if (!empty($whereClause)) {
366 $whereClause .= ' AND ';
367 }
368 $whereClause .= 'disable = 0';
369 }
370 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('serialized_task_object', 'tx_scheduler_task', $whereClause);
371 if ($res) {
372 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
373 $task = unserialize($row['serialized_task_object']);
374 $task->setScheduler();
375 $tasks[] = $task;
376 }
377 $GLOBALS['TYPO3_DB']->sql_free_result($res);
378 }
379 return $tasks;
380 }
381 }
382
383 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler.php']) {
384 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler.php']);
385 }
386
387
388 ?>