topherg
topherg

Reputation: 4293

Close a Connection, but continue to do Processing

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)?

Upvotes: 1

Views: 386

Answers (3)

Halcyon
Halcyon

Reputation: 57719

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

Upvotes: 3

Daryl Gill
Daryl Gill

Reputation: 5524

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.

Upvotes: -1

Rob W
Rob W

Reputation: 9142

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

Upvotes: 1

Related Questions