简体   繁体   中英

Ajax/PHP - should I use one long running script or polling?

I have a PHP script that is kicked off via ajax. This PHP script uses exec() to run a separate PHP script via the shell.

The script that is called via exec() may take 30 seconds or so to complete. I need to update the UI once it is finished.

Which of these options is preferred?

a) Leave the HTTP connection open for the 30 seconds and wait for it to finish.
b) Have exec() run the PHP script in the background and then use ajax polling to check for completion (every 5 seconds or so).
c) Something else that I haven't thought of.

Thank you, Brian

Poll the server for updates every few seconds. When you leave connections open for that long a period of time there's always the possibility that they may be dropped by the server or their browser (browsers timeout if an HTTP request takes too long).

Option b) feels a little too stateful to me. Does the server need to receive a request once the 30 seconds are done, else it gets into a bad state? (like it doesn't relinquish resources or something of the like) If so, definitely go with a) methinks.

As for c), maybe you'll find something on the AJAX Pattern's Web Site under Browser-Server Diaglog .

The AJAX option seems good to me. One alternative is Comet (Ajax Push) style to minimize required traffic: Server sends signal to client(browser) when it has to say something (update UI).

a) could have problems with timeout and locks server requests (usually you set limit server accepts connections). you could lock the server if many users add requests on the server. on http environment i would only keep open connections as long as necessary.

b) if it is 30 seconds long i would poll not so often like each second. i would increase the polling time. is the execution time always 30 seconds? example polling style (payload is json):


# trigger job/execution
POST /job
=> response gives 301 redirect to /jobs/{job-id}

# polling
GET /jobs/{job-id}
=> {status:busy}
or
=> {status:completed,result:...}
 

but in the end it depends on the problem, i like b) more but it adds more effort to implement. maybe you have more details? is it a high traffic scenario?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM