1

I have a PHP site that performs Cron's that are triggered during client executions instead of a Cron manager. One of the Cron's that are performed takes a few seconds to execute, and it keeps the connection between the Client and the Server open until it is complete. Although I know I can set up a Cron to be fired from the Server instead of during Client runs, I would like to know if it is possible without following that format.

So, can the PHP script send a command to Apache (or whatever server it is hosted on) to close the connection between the Client and the Server, but continue to functions (so, without exiting)?

topherg
  • 4,203
  • 4
  • 37
  • 72

3 Answers3

4

This works on Apache (and apparently not on IIS with FastCGI)

<?php
ignore_user_abort(true); // make sure PHP doesn't stop when the connection closes

// fire and forget - do lots of stuff so the connection actually closes
header("Content-Length: 0");
header("Connection: Close");
flush();
session_write_close(); // if you have a session

do_processing();
// don't forget to `set_time_limit` if your process takes a while
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • This usually does not work on IIS with FastCGI as it reuses the same instance for multiple requests so it waits till it's done. But it does work well on Apache. – CodeAngry Jul 02 '13 at 17:26
  • Hmm, its strange. Something is defiantly happening, I have included those lines (and modified `Content-Length: 0` to determine the size of what is to be sent so far, but the receiving icon (at the top on chrome) spins (unlike before), but still waits for the entire code to complete before updating the window, so the correct data is being sent, but the connection is still remaining open until the end of the cron – topherg Jul 02 '13 at 17:36
  • Ah, just had to add `fastcgi_finish_request();`(i've updated the question) – topherg Jul 02 '13 at 17:40
  • If your server compresses output, you need to disable it with header("Content-Encoding: none\r\n"); – Bobby Tables Sep 25 '13 at 14:41
1

You can use shell to call the PHP binary... example:

shell("php -f /path/to/cronfile.php > /dev/null 2>/dev/null &"); which will run and not wait for a return.

See Asynchronous shell exec in PHP

Community
  • 1
  • 1
Rob W
  • 9,134
  • 1
  • 30
  • 50
-1

Typically There is two forms of execution.

Client sided: The client will remain on the page and the page will continue to process the commands given until completion.

Server Sided: The client will navigate to a page & You make a switch in the database:

  UPDATE Table SET PendinCron=1 WHERE IdentiferCol=$IdentiferData

Then you will have a Cronjob being run at X interval and will only process when the PendinCron is equal to one, if it is not. The Cron will not execute the required task.

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69