Upon saving a new post (of a certain post type), a given operation has to run. The problem is that the operation is calling an external (slow) API, which means that the (not logget in) end-user might having to wait for 20-30 seconds, upon creating this new post (not good for the user-experience).
My own solution (not implemented yet)
- User clicks ‘create’.
- The post gets saved (without calling that external API).
- Upon that initial save-operation a post_meta-field is saved:
update_post_meta( "automation_operation_has_run", false, $post->ID );
- A cron-job runs every minute, getting all posts where
falseand calls that external API for the given post. This call obviously also does this:
update_post_meta( "automation_operation_has_run", true, $post->ID );(to stop it from triggering twice).
… It just feels kind of clumbsy. And a bit error-prone, in case the external-API-call takes longer than 1 minute to repond (endless loop, accidentally running the automation operation twice, etc.).
Are there a better way to do this, to avoid using a cron-job? Are there a callback-function, when a post has finished saved, that can be utilized, without the end-user has to wait for that to finish?
- The post type is a ‘wc_order’ on a WooCommerce site.
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
If you don’t have control over the API, you’re doing it almost right. That is what cron jobs are for.
What needs to be avoided is possible overlapping API calls that do the same thing. Why not instead have a meta field
automation_operation_status that stores the … status? Like
Then, in your cron job you just query those that are pending. And if it’s really that long of a process, you could even limit it to one or two jobs per run.
Just gotta play with the cron job frequency and avoid PHP timeouts.
In the end, the ideal solution would be the API itself offering a fast acting queue where jobs can be stored for later processing. On top of that a service where processing status can be queried. Or a service that posts back to the WordPress installation on job completion (if that needs that info).
All that you would also only call via cron jobs.
This way you put minimum stress on the frontend facing server.