1. Go to this page and download the library: Download shewa/wp-job-queue library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
shewa / wp-job-queue example snippets
use WpJobQueue\Database\Migrator;
register_activation_hook( __FILE__, function () {
Migrator::install();
} );
use WpJobQueue\Bootstrap;
use WpJobQueue\JobManager;
// Boot on plugins_loaded
Bootstrap::init( [
'jobs' => [
MyCustomJob::class,
],
] );
// Dispatch a job
$job_id = JobManager::instance()->dispatch(
MyCustomJob::class,
[ 'step' => 0 ]
);
if ( is_wp_error( $job_id ) ) {
// Handle error
}
namespace MyPlugin\Jobs;
use WpJobQueue\AbstractJob;
use WpJobQueue\JobRecord;
use WpJobQueue\JobResult;
use WpJobQueue\JobStatus;
class MyCustomJob extends AbstractJob {
public static function getType(): string {
return 'my_custom_job';
}
public static function getLabel(): string {
return 'My Custom Job';
}
public function handle( JobRecord $job ): JobResult {
if ( JobStatus::CANCELLED === $job->status ) {
return JobResult::failed( 'Job was cancelled.' );
}
$payload = $job->payload;
$step = (int) ( $payload['step'] ?? 0 );
// Do one chunk of work…
$step++;
$payload['step'] = $step;
if ( $step < 10 ) {
return JobResult::continue(
$payload,
$step * 10,
sprintf( 'Processing step %d…', $step )
);
}
return JobResult::complete(
[ 'done' => true ],
'All steps finished.'
);
}
}