facebook-for-woocommerce icon indicating copy to clipboard operation
facebook-for-woocommerce copied to clipboard

Avoid use of `init` or `admin_init` hooks for regular tasks, prefer `Heartbeat` system

Open danielbitzer opened this issue 4 years ago • 3 comments

Related issues: #1632 #1796

This plugin performs some actions, like scheduling tasks, on every request which unnecessarily degrades the whole site's performance. This is especially impactful on larger sites.

Examples:

Update - Heartbeat system implemented in #1953

The below "heartbeat" approach is now implemented. There are more places it could be used (see checklist above, or search for init or admin_init. Keeping this issue open to improve these over time.

Solutions:

WP CRON - Status checker

My suggestion is to implement a "heartbeat style" WP Cron job i.e. a cron job that runs every hour. This cron job would only be responsible for scheduling an action with Action Scheduler in order to minimize our impact on WP Cron requests.

Then we would move anything from init to this scheduled action's hook.

Why WP Cron? WP Cron events are storead in an autoloaded option so the performance impact of reading is extremely low. We should be able to confidently run the following code on every request.

// Schedules the heartbeat cron scheduler
add_action( 'init', function() {
	if ( ! wp_next_scheduled( 'facebook_for_woocommerce_hourly_heartbeat_cron' ) ) {
		wp_schedule_event( time(), 'hourly', 'facebook_for_woocommerce_hourly_heartbeat_cron' );
	}
} );

// Schedules the heartbeat Action Scheduler action
add_action( 'facebook_for_woocommerce_hourly_heartbeat_cron', function() {
	as_schedule_single_action( time() + 60, 'facebook_for_woocommerce_hourly_heartbeat' );
} );

@woocommerce/tetris please let me know your thoughts on this approach and suggest any alternatives, thanks!

danielbitzer avatar May 13 '21 01:05 danielbitzer

Reopening since there are other tasks running on init than can use the heartbeat added in #1953.

danielbitzer avatar May 19 '21 00:05 danielbitzer

Reopening since there are other tasks running on init than can use the heartbeat added in #1953.

@danielbitzer Might be worth opening specific tasks, if we know what they are – or if we need to investigate, open a new issue scoped to that. I think your work has addressed this issue - we now have a heartbeat capability 🚀

haszari avatar May 19 '21 01:05 haszari

I've refreshed the title and description now that the heartbeat mechanism is implemented. We can keep this issue around to migrate the remaining tasks over time.

haszari avatar Jun 02 '21 03:06 haszari

The last item is no longer needed as Order class has been removed with #2390.

I will therefore close this issue.

rawdreeg avatar Nov 30 '22 16:11 rawdreeg