3 * Job queue task base code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @defgroup JobQueue JobQueue
25 * Class to both describe a background job and handle jobs.
26 * The queue aspects of this class are now deprecated.
27 * Using the class to push jobs onto queues is deprecated (use JobSpecification).
31 abstract class Job
implements IJobSpecification
{
35 /** @var array Array of job parameters */
38 /** @var array Additional queue metadata */
39 public $metadata = [];
44 /** @var bool Expensive jobs may set this to true */
45 protected $removeDuplicates;
47 /** @var string Text for error that occurred last */
52 * @return bool Success
54 abstract public function run();
57 * Create the appropriate object to handle a specific job
59 * @param string $command Job command
60 * @param Title $title Associated title
61 * @param array $params Job parameters
65 public static function factory( $command, Title
$title, $params = [] ) {
68 if ( isset( $wgJobClasses[$command] ) ) {
69 $class = $wgJobClasses[$command];
71 $job = new $class( $title, $params );
72 $job->command
= $command;
77 throw new InvalidArgumentException( "Invalid job command '{$command}'" );
81 * @param string $command
83 * @param array|bool $params Can not be === true
85 public function __construct( $command, $title, $params = false ) {
86 $this->command
= $command;
87 $this->title
= $title;
88 $this->params
= is_array( $params ) ?
$params : []; // sanity
90 // expensive jobs may set this to true
91 $this->removeDuplicates
= false;
95 * Batch-insert a group of jobs into the queue.
96 * This will be wrapped in a transaction with a forced commit.
98 * This may add duplicate at insert time, but they will be
99 * removed later on, when the first one is popped.
101 * @param Job[] $jobs Array of Job objects
103 * @deprecated since 1.21
105 public static function batchInsert( $jobs ) {
106 wfDeprecated( __METHOD__
, '1.21' );
107 JobQueueGroup
::singleton()->push( $jobs );
114 public function getType() {
115 return $this->command
;
121 public function getTitle() {
128 public function getParams() {
129 return $this->params
;
133 * @return int|null UNIX timestamp to delay running this job until, otherwise null
136 public function getReleaseTimestamp() {
137 return isset( $this->params
['jobReleaseTimestamp'] )
138 ?
wfTimestampOrNull( TS_UNIX
, $this->params
['jobReleaseTimestamp'] )
143 * @return int|null UNIX timestamp of when the job was queued, or null
146 public function getQueuedTimestamp() {
147 return isset( $this->metadata
['timestamp'] )
148 ?
wfTimestampOrNull( TS_UNIX
, $this->metadata
['timestamp'] )
153 * @return int|null UNIX timestamp of when the job was runnable, or null
156 public function getReadyTimestamp() {
157 return $this->getReleaseTimestamp() ?
: $this->getQueuedTimestamp();
161 * Whether the queue should reject insertion of this job if a duplicate exists
163 * This can be used to avoid duplicated effort or combined with delayed jobs to
164 * coalesce updates into larger batches. Claimed jobs are never treated as
165 * duplicates of new jobs, and some queues may allow a few duplicates due to
166 * network partitions and fail-over. Thus, additional locking is needed to
167 * enforce mutual exclusion if this is really needed.
171 public function ignoreDuplicates() {
172 return $this->removeDuplicates
;
176 * @return bool Whether this job can be retried on failure by job runners
179 public function allowRetries() {
184 * @return int Number of actually "work items" handled in this job
185 * @see $wgJobBackoffThrottling
188 public function workItemCount() {
193 * Subclasses may need to override this to make duplication detection work.
194 * The resulting map conveys everything that makes the job unique. This is
195 * only checked if ignoreDuplicates() returns true, meaning that duplicate
196 * jobs are supposed to be ignored.
198 * @return array Map of key/values
201 public function getDeduplicationInfo() {
203 'type' => $this->getType(),
204 'namespace' => $this->getTitle()->getNamespace(),
205 'title' => $this->getTitle()->getDBkey(),
206 'params' => $this->getParams()
208 if ( is_array( $info['params'] ) ) {
209 // Identical jobs with different "root" jobs should count as duplicates
210 unset( $info['params']['rootJobSignature'] );
211 unset( $info['params']['rootJobTimestamp'] );
212 // Likewise for jobs with different delay times
213 unset( $info['params']['jobReleaseTimestamp'] );
214 // Queues pack and hash this array, so normalize the order
215 ksort( $info['params'] );
222 * Get "root job" parameters for a task
224 * This is used to no-op redundant jobs, including child jobs of jobs,
225 * as long as the children inherit the root job parameters. When a job
226 * with root job parameters and "rootJobIsSelf" set is pushed, the
227 * deduplicateRootJob() method is automatically called on it. If the
228 * root job is only virtual and not actually pushed (e.g. the sub-jobs
229 * are inserted directly), then call deduplicateRootJob() directly.
231 * @see JobQueue::deduplicateRootJob()
233 * @param string $key A key that identifies the task
234 * @return array Map of:
235 * - rootJobIsSelf : true
236 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
237 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
240 public static function newRootJobParams( $key ) {
242 'rootJobIsSelf' => true,
243 'rootJobSignature' => sha1( $key ),
244 'rootJobTimestamp' => wfTimestampNow()
249 * @see JobQueue::deduplicateRootJob()
253 public function getRootJobParams() {
255 'rootJobSignature' => isset( $this->params
['rootJobSignature'] )
256 ?
$this->params
['rootJobSignature']
258 'rootJobTimestamp' => isset( $this->params
['rootJobTimestamp'] )
259 ?
$this->params
['rootJobTimestamp']
265 * @see JobQueue::deduplicateRootJob()
269 public function hasRootJobParams() {
270 return isset( $this->params
['rootJobSignature'] )
271 && isset( $this->params
['rootJobTimestamp'] );
275 * @see JobQueue::deduplicateRootJob()
276 * @return bool Whether this is job is a root job
278 public function isRootJob() {
279 return $this->hasRootJobParams() && !empty( $this->params
['rootJobIsSelf'] );
283 * Insert a single job into the queue.
284 * @return bool True on success
285 * @deprecated since 1.21
287 public function insert() {
288 JobQueueGroup
::singleton()->push( $this );
295 public function toString() {
296 $truncFunc = function ( $value ) {
297 $value = (string)$value;
298 if ( mb_strlen( $value ) > 1024 ) {
299 $value = "string(" . mb_strlen( $value ) . ")";
305 if ( $this->params
) {
306 foreach ( $this->params
as $key => $value ) {
307 if ( $paramString != '' ) {
310 if ( is_array( $value ) ) {
312 foreach ( $value as $k => $v ) {
313 if ( is_scalar( $v ) ) {
314 $filteredValue[$k] = $truncFunc( $v );
316 $filteredValue = null;
320 if ( $filteredValue && count( $filteredValue ) < 10 ) {
321 $value = FormatJson
::encode( $filteredValue );
323 $value = "array(" . count( $value ) . ")";
325 } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
326 $value = "object(" . get_class( $value ) . ")";
329 $paramString .= "$key={$truncFunc( $value )}";
334 foreach ( $this->metadata
as $key => $value ) {
335 if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
336 $metaString .= ( $metaString ?
",$key=$value" : "$key=$value" );
341 if ( is_object( $this->title
) ) {
342 $s .= " {$this->title->getPrefixedDBkey()}";
344 if ( $paramString != '' ) {
345 $s .= " $paramString";
347 if ( $metaString != '' ) {
348 $s .= " ($metaString)";
354 protected function setLastError( $error ) {
355 $this->error
= $error;
358 public function getLastError() {