Jonathan
Jonathan

Reputation: 3534

Can I have an hour-long sleep in a website PHP script?

I have a PHP script that processes my email subscriptions.

It does something like:

foreach email to be sent:
    mailer->send-email
    print "Email sent to whoever."

I'm now encountering rate-limiting by my web host. The mailing library has a built in throttler that will sleep to ensure I stay under the rate. However, this could result in the web page taken multiple hours to actually load.

Will the client side browser ever give up on the page loading? Any suggested better solutions to this?

Upvotes: 1

Views: 858

Answers (2)

goat
goat

Reputation: 31813

You may not care, but even if you coerce this script into staying alive, you shouldn't purposely run a long running script through the webserver. Webserver's use resource heavy threads or processes to run your script, and they have a finite amount of them available to server web requests. A long running script basically takes one of them out of the pool of processes that can be used to server web visitors.

Instead, use a cron job which executes the php binary directly. Specifically, do not use wget or lynx or any other web browser like program as part of the cron job, because those methods run the script through the webserver. The cron command should include something like

php /full/path/to/the/script.php

Upvotes: 1

David
David

Reputation: 218808

Why is this being done on a webpage load? This should be an off-line back-end process which is scheduled to run. (Look into cron for scheduling tasks.)

Any long running process should be delegated to a back-end service to handle that process. Application interfaces (such as a web page) should respond back to the user as quickly as possible instead of forcing the user to wait (for upwards of an hour?) for a response.

The application can track progress, usually by means of some shared data source (a simple database, for example), of the back-end process and present that progress to the user. That's fine. But the process itself should happen outside of the application.

For example, at a high level...

  1. Have a PHP script scheduled to run to process the emails.
  2. When the script starts, save a record to a database indicating that it's started.
  3. Each time the script reaches a milestone of some kind, update the database record to indicate this.
  4. When the script finishes, update the database record to indicate this.
  5. Have a web application which checks for that database record and shows the user the current status of the back-end process.

Upvotes: 4

Related Questions