Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a note about process instantiation #57

Merged
merged 1 commit into from
Jul 30, 2020

Conversation

markjaquith
Copy link
Contributor

Instantiation should happen unconditionally. If you only instantiate on-demand when you're pushing to the queue, it won't work.

I was confused about this. I had this code:

public function add_items( array $items = [] ) {
	$job = new MyJob();

	foreach ( $items as $item ) {
		$job->push_to_queue( $item );
	};

	$job->save()->dispatch();
}

This did not work, because on requests where I was not calling add_items(), MyJob() wasn't being instantiated.

Instantiation should happen unconditionally. If you only instantiate on-demand when you're pushing to the queue, it won't work.
@acafourek
Copy link

Took me awhile to discern what this meant, and while it's obvious in retrospect, I wonder if we could phrase this guidance more explicitly? My first crack:


The core WP_Background_Process class also processes the queue of tasks to be run and to do so, it needs to be instantiated on every page load. If you only load the class when you're adding things to the queue, that core class wont ever be loaded to actually do anything with the queue. So, make sure that you're doing something like this:

add_action('init', function(){
    new myQueueJob();
});

You'll still need to instantiate later when adding to the queue, like this:

     $background = new myQueueJob();
     $background->push_to_queue($item )->save()->dispatch();

This way, the core class can add items to the queue and work with that queue every time WP gets loaded.

@polevaultweb polevaultweb merged commit 6859922 into deliciousbrains:master Jul 30, 2020
@markjaquith
Copy link
Contributor Author

Perhaps a bigger issue is that constructor side effects aren't a good pattern. This issue would be more obvious if you had to call $job->work(); or $job->listen();. It wasn't obvious to me that new-ing up an object would do anything except provide me that object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants