2

I am writing a plugin and using admin-ajax. It's a long-running function - that is, it's connecting to an API and loading in posts. This could take 5-10 minutes sometimes. Seems like after 1-2 minutes my AJAX call gets a "502 (Bad Gateway)" error response, and the work on the PHP side stops at that exact moment.

  1. Is there a timeout on what you can do with admin-ajax?
  2. Is there a better way to do "long running" activities in a plugin other than admin-ajax?

Thanks!

  • A 502 sounds like you're overloading your server, maybe you should request fewer posts and look at making your system more efficient. 502 gateway errors are lower down the stack, and come from the Apache/Nginx levels not the PHP/WordPress levels – Tom J Nowell May 15 '15 at 2:00
4
+50

There is always a timeout, be it TCP or the PHP execution time ( unless you configure your server in a weird way, PHP will kill long running tasks ).

If you need to do a lot of work you should:

Break it into smaller pieces

Plugins like regen thumbnails retrieve a list of items to do work on, then go through the list in small fast batches keeping track of what's been done as it goes along. You can do 10 minutes worth of work, but instead of 1 million things in 1 request, it's better to do 1 thing in 1 million requests.

WP CLI

Expensive lengthy work shouldn't be done on the frontend. It should be done on the command line. This is the best method and recommended.

Implement a WP CLI command that does what you need to do, and run it. This bypasses the PHP execution timeout completely, as well as any connection timeouts that might happen. WP CLI commands could run for hours if your code has enough system resources and cleans up after itself to prevent memory leaks. If you need to pass in data, do so using parameters.

if you don't have CLI access, you're either using a managed host service, or a shared hosting service, in which case you should either move host ( shared hosting is problematic ), or download the site to your local machine and run the CLI command locally, then upload the results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.