I'm writing a plugin that performs several actions, one of which is a complex routine that parses and imports a large Excel spreadsheet (don't ask). I want this routine to run as a background task, using the action-scheduler
plugin, to avoid UI sluggishness and server timeouts.
Specifically, I want to run this action using wp-cli
and the server's cron instead of WP-Cron because, when run using WP-Cron, the server kills the task after about a minute of processing.
Here's the salient portions of my code (function names have been changed):
From the __construct method of my importer class:
add_action(
'myplugin_background_file_import',
array($this, 'my_long_import_routine'),
PHP_INT_MAX, // lowest possible priority
8 // argument count
);
// ignore this hook so I can run it via server cron
add_action('action_scheduler_before_execute', function ($action_id) {
$action = ActionScheduler::store()->fetch_action($action_id);
$hook = $action->get_hook();
if ('myplugin_background_file_import' === $hook) {
error_log('ActionScheduler — skipping action hook: ' . $hook);
throw new Exception('Skipping this action as it is handled by server cron.');
}
});
// much later in a different method //
as_enqueue_async_action(
'myplugin_background_file_import',
array(/* associative array of the 8 args previously mentioned */),
'my_group',
false,
255
);
The task scheduling works correctly (screenshot) and the action_scheduler_before_execute
action filters the hook correctly, so WP-Cron does not run it.
The trouble is when I run this command, I don't get the expected result:
wp action-scheduler run --hooks="myplugin_background_file_import"
It will tell me that several tasks compete (from dozens to several hundred, depending on when I run it—it varies unpredictably), but the task in Scheduled Actions stays at "pending" no matter what I do.
Near as I can tell, I'm doing everything correctly. Am I incorrect? Is there a logic error here that I'm missing? This is my first serious use of action-scheduler
so I'm definitely not ruling out user error.
Any input would be appreciated; if I've left anything out or can add more context, please let me know. Thanks!
action-scheduler
plugin's support team about this. Third-party plugin support is off topic here.