I need a second opinion and a sanity check if the solution I\'m trying to implement will work.
I need to implement a way to run a script that would otherwise be blocking if I would run it using just ajax (and would probably timeout). So my idea is to do the following:
Have a button in the admin that, when clicked, would trigger an ajax call, which would schedule the event immediately. This scheduled event would be done using wp_schedule_event()
(https://developer.wordpress.org/plugins/cron/scheduling-wp-cron-events/).
In this event, on the first call, I\'d add a flag in the database that will signal that the event is running. This is used as a way to check if the event is running in the background so that I can do a check, in ajax, if the job is running in the background - if it is, don\'t run it again.
Now, because it\'s a scheduled, recurring job, I\'d need a way to not spawn it again all the time, even if it finished. What I was thinking is adding a check in the place where I add my add_action( \'bl_cron_hook\', \'bl_cron_exec\' );
hook for
if ( ! wp_next_scheduled( \'bl_cron_hook\' ) ) {
wp_schedule_event( time(), \'five_seconds\', \'bl_cron_hook\' );
}
The add_action
call and the function to execute bl_cron_exec
would be in a separate class, and the wp_schedule_event
would be in the ajax callback.
And also, if the flag in the database is finished
I would unschedule the job (in the class where the bl_cron_exec
is).
What concerns me is, if my job is running in the background, and I unschedule the job, will this terminate the already running job, or am I safe and this job will continue working (or fail, in which case I will write to the db that the call failed). Because a running job is started in a separate process if I\'m not mistaken. So a job that is running cannot be stopped, or can it?
Is there a smarter way of implementing background jobs in WordPress? I don\'t want a plugin, I need my own implementation (business reasons).
Basically, some kind of a flow would be:
ajax:
NO JOB RUNNING:
check if job is running - no
schedules event (in 1 sec or less)
triggers flag in the database - job running
exit with code - event started (scheduled)
JOB RUNNING:
check if job is running - yes
unschedule job
exit with code - event running
event:
If the database trigger says: running (the wp_next_scheduled should take care of that) - don\'t start new schedule (return? or unschedule).
If the database trigger says: finished, continue running the event.