Jake
Jake

Reputation: 1205

Executing PHP code after a specific time

Let's say that there are two PHP functions.

function first()
{

     $keyword = $this->input->post('keyword');

     //search for the result and show it to users.
     $this->search->search($keyword);

     //send the keyword to save it into the db.
     $this->second($keyword);
}


function second($keyword)
{
      //saving a search keyword in the db
}

I would like to send the result as soon as possible and save the search word into DB.

However, I want to run the second script later after specific time.

because I want to deliver the search result as soon as possible to my customer.

Is there a way to run second PHP script after a user run the first PHP script?

* I don't want to use Cron Job
* I wanna run those two script separatly. 
* don't want to use sleep because it will stop the first script for certain times.

Upvotes: 4

Views: 5450

Answers (3)

Bob Davies
Bob Davies

Reputation: 2282

You'll need to route it back round to your server, but this asynchronous php approach works quite nicely (I've been using it for about a year to do almost exactly what you seem to be doing).

See: How to run the PHP code asynchronous

Upvotes: 3

eis
eis

Reputation: 53462

Instead of making a web request from PHP, as suggested by Bob Davies, I would initiate a new HTTP request from the html page after the page has been shown.

For example:

  1. Client makes an HTTP request (search)
  2. Server gets the stuff and returns results to the end user
  3. The result HTML contains a snippet, such as < img src="empty.gif?searchterm=mysearch"/> which initiates another request when browser renders the html
  4. When that another request hits your server, you can save the search to DB

Similar methods are used to do for example client tracking, when you don't want the end user having to wait your metrics stuff. Some points:

  • It is quite simple to understand, implement and debug, which (to my opinion) doing HTTP requests on the server side aren't
  • It's more scalable
  • It doesn't require having javascript on, just a browser rendering the HTML
  • The target can be any server anywhere which doesn't have to be accessible from your web server, just to end user.

Upvotes: 1

Nadav S.
Nadav S.

Reputation: 2459

If you want to use PHP only then as far as I know, you can use sleep(), but it delays the execution of the code.

I think the easiest way to delay the job is with AJAX. Simply put the second function inside another PHP document and call XMLHTTPRequest() or $.ajax (if you want to use jQuery), and delay the code for some seconds. You can do that with setInterval(), or with delay() (jQuery).

Simply write

delay(2000).function(){
    //saving a search keyword in the db
}

Remember that here you should use AJAX and not PHP code.

Upvotes: 0

Related Questions