user1424232
user1424232

Reputation: 117

Best way to continue a timed out script in php?

I have a php file I wrote that checks for new files in certain folders, then emails off the newest files since the last run. Sometimes this can be 10-15 files being attached to an email. I am using swiftmailer to send the emails.

This script can cycle through up to 50 customers, and each customer can have files which need to be emailed. Often times, this will timeout via PHP and throw an error. I've been trying to track where it left off by writing customer numbers to a file via php.

How can I use PHP to say "If there is an abrupt exit or error, then re-run this file."

Another way to say this is.... when I get a timeout error, or any other error, can I simply reload another PHP file to continue where I left off?

This doesn't seem like the cleanest way to accomplish my task, so I'm open to suggestions.

Upvotes: 0

Views: 120

Answers (1)

George Cummins
George Cummins

Reputation: 28926

You can track the files to be processed by writing to a flat file or database, removing the entry for each file as it is completed. When the script restarts, read the list of files to be processed and continue where you left off.

Additionally, consider increasing the timeout setting in php.ini if you know that your script regularly requires more time.

In the event that you need to restart the script continually until the processing is completed, consider the following scenario:

  • Start the script via cron every five minutes (or appropriate interval)
  • The script writes a PID file
    • If the script finds that the PID file already exists, the previous script crashed, so start processing the log again.
  • Check the database for the last successful run time.
    • If the last successful run time was less than the minimum (the interval at which you currently run the script), delete the PID and exit.
    • If the last successful run time was more than the minimum, process the files, delete the PID, and exit.

The use of a PID file is not strictly necessary; you can get the same information by checking to see if the log exists and has entries. However, the use of a PID is traditional and provides a quick and cheap method of determining whether the previous process completed successfully.

Upvotes: 3

Related Questions