PHP code example of a5hleyrich / wp-queue

1. Go to this page and download the library: Download a5hleyrich/wp-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/ */

    

a5hleyrich / wp-queue example snippets




use WP_Queue\Job;

class Subscribe_User_Job extends Job {

	/**
	 * @var int
	 */
	public $user_id;

	/**
	 * Subscribe_User_Job constructor.
	 *
	 * @param int $user_id
	 */
	public function __construct( $user_id ) {
		$this->user_id = $user_id;
	}

	/**
	 * Handle job logic.
	 */
	public function handle() {
		$user = get_user_by( 'ID', $this->user_id );

		// Process the user...
	}

}

wp_queue()->push( new Subscribe_User_Job( 12345 ) );

wp_queue()->push( new Subscribe_User_Job( 12345 ), 3600 );

wp_queue()->cron();

wp_queue()->cron( 3 );

class Connection extends DatabaseConnection {
    public function __construct( $wpdb, array $allowed_job_classes = [] ) {
        // If a connection is always dealing with the same Jobs,
        // you could explicitly set the allowed job classes here
        // rather than pass them in.
        if ( empty( $allowed_job_classes ) ) {
            $allowed_job_classes = [ Subscribe_User_Job::class ];
        }

        parent::__construct( $wpdb, $allowed_job_classes );

        $this->jobs_table     = $wpdb->base_prefix . 'myplugin_subs_jobs';
        $this->failures_table = $wpdb->base_prefix . 'myplugin_subs_failures';
    }
}

class Subscribe_User_Queue extends Queue {
    public function __construct() {
        global $wpdb;

        // Set up custom database queue, with list of allowed job classes.
        parent::__construct( new Connection( $wpdb, [ Subscribe_User_Job::class ] ) );

        // Other set up stuff ...
    }
}

class MyPlugin {
    /**
     * @var Subscribe_User_Queue
     */
    private $queue;

    public function __construct() {
        // Part of bring-up ...
        $this->queue = new Subscribe_User_Queue();
        
        // Other stuff ...
    }

    protected function subscribe_user( $user_id ) {
        $this->queue->push( new Subscribe_User_Job( $user_id ) );
    }

    /**
     * Triggered by cron or background process etc.
     *
     * @return bool
     */
    protected function process_queue_job() {
        return $this->queue->worker()->process();
    }
}

add_filter( 'wp_queue_default_connection', function() {
	return 'sync';
} );