views:

58

answers:

2

I'm using $r->pool->cleanup_register(\&cleanup); to run a subroutine after a page has been processed and printed to the client. My hope was that the client would see the complete page, and Apache could continue doing some processing in the background that takes a few seconds.

But the client browser hangs until cleanup sub has returned. Is there a way to get apache to finalise the connection with the client before all my code has returned?

I'm convinced I've done this before, but I can't find it again.

A: 

You want to flush the buffer. It doesn't finalize the connection, but your client will see the output before the task completes.

sub handler {
      my $r = shift;
      $r->content_type('text/html');
      $r->rflush; # send the headers out

      $r->print(long_operation());
      return Apache2::Const::OK;
  }
nont
It sounds to me like the OP wants to run the long operation in the cleanup hook, which would be called after `handler` returns. So I don't think flushing the output buffer would necessarily help in this situation.
friedo
hmmm, not sure. I read the problem as "the client doesn't see any output until after this long running task has completed." If that's the real issue, then flushing should force the output to be sent to the user's browser. On the other hand, if the output is already displayed and just wants to close the connection, then I agree with you. I guess Brian will let us know.
nont
Thanks nont, that's a useful one to know. But friedo interpreted my scribblings correctly. I want it to appear to the client that the page has completely loaded. Put another way, I don't want this long process to be aborted if the client closes their browser.
aidan
+1  A: 

Use a job queue system and do the long operation completely asynchronously -- just schedule the operation during the web request. A job queue also handles peak load situations better than doing something expensive within the web server processes themselves.

haa
++ I agree, if at all possible do the task outside of the web server. If there are any problems (waiting for locks, etc), this can cause an apache instance to be unavailable to serve requests, and uses all of the memory of Apache to do a (possibly simple) job. I've seen this cause big problems in the past... If you can't set up a cron job or similar in your hosting environment, see if you can fork/exec a separate process to handle this task.
FalseVinylShrub