0

Let's assume I have two PHP scripts, s1.php and s2.php. Let's also assume that s2.php takes about 30 minutes of running.

I would like to use s1.php to call s2.php asynchronously. When s2.php is called, it will run on its own without returning any value to s1.php. s1.php would not wait for s2.php to finish; s1.php will continue the next command, while s2.php starts on its own.

So here is the pseudo code for s1.php

  1. Do something
  2. Call s2.php
  3. Continue s1.php, while s2.php is running (this step does not need to wait for s2.php to return in order to continue, it immedieately startes after s2.php starts).

How can I do that?

IMPORTANT NOTE: I am using a shared hosting environment

Greeso
  • 7,544
  • 9
  • 51
  • 77
  • 3
    Why don't you start s2 as a cli process? (Via cron, for example) – AD7six Feb 13 '14 at 22:29
  • This doesn't probably qualify as full answer, but you could `curl` your `s2.php` from `s1.php` and use some of techniques described here: http://stackoverflow.com/questions/3833013/continue-php-execution-after-sending-http-response to quickly end response in `s2.php` and continue its execution "asynchronously". – Kuba Wyrostek Feb 13 '14 at 22:52
  • a basic answer: `exec('php s2.php');` –  Feb 13 '14 at 23:12

2 Answers2

0

Out of the box, PHP does not support async processing or threading. What you're most likely after is Queueing and/or Messaging.

This can be as simple as storing a row in a database in s1.php and running s2.php on a cron as suggested in the comments, which reads that database, pulls out new rows and executes whatever logic you need.

It would be up to you to clean up - making sure you aren't reprocessing the same rows multiple times.

Other solutions would be using something like RabbitMQ or IronMQ. IronMQ might be a good place to look because its a cloud based service which would work well in your shared hosting environment and they allow for a 'dev tier' account which is free and probably far more api calls then you'll ever need.

Other fun things to look at is ReactPHP as that does allow for non-blocking io in php.

kmfk
  • 3,821
  • 2
  • 22
  • 32
0

afaik, there's no good way to do this :/ you can use proc_open / exec ("nohup php5 s2.php") ~ , or $cmh=curl_multi_init(); $ch=curl_init("https://example.org/s2.php"); curl_multi_add_handle($chm,$ch);curl_multi_exec($chm,$foo); though (or if you don't have curl, substitute with fopen... or if allow_url_fopen is false, you can even go as far as socket_create ~~ :/ )

hanshenrik
  • 19,904
  • 4
  • 43
  • 89