0

I have 2 functions, let's call them login and doSomething and currently, I implemented them this way,

$member=$this->login();
$this->doSomething($member);

//show welcome page When a user logs in, I want to do some stuff but it takes around 20 seconds or more to complete. Is there any ways where after login() is run, it will show the welcome page immediately while the method doSomething() is being executed separately. The method doSomething() doesn't return any values thus does not affect the welcome page.

Gokul Gowda
  • 177
  • 1
  • 13
  • make use of ajax: https://en.wikipedia.org/wiki/Ajax_(programming) – Vickel Sep 04 '18 at 17:28
  • 1
    while making use ajax solves your problem, you can also take a look into `Asynchronous Resque Workers` and queue up this function execution, basically making it a child process... https://github.com/chrisboulton/php-resque – popeye Sep 04 '18 at 17:37
  • If your doSomething function isn't needed by the user, then use some queuing product like Rabbit or Beanstalk or Redis. Set up a process that is already running to grab the messages from the queue and process them. – ryantxr Sep 04 '18 at 19:59

2 Answers2

0

Please try the following.

ob_start();

$member = $this->login();

ob_end_flush();
ob_flush();
flush();

$this->doSomething($member);

If you do not want to print anything after login, you can use:

ob_start();
$this->doSomething($member);
ob_end_clean();

Also using Ajax from the front site's login page(after loading), you can start processing $this->doSomething($member); in another ajax call in the back end silently.

There are other ways for achieving threading, pseudo threading like behaviour. But these are the easiest one for your scenerio :)

You can check WorkerThreads also. Their implementation example documentation are available in the net.

Tanvir Ahmed
  • 483
  • 3
  • 10
  • 1
    This is rather messy. It would be a lot safer to execute the method via register_shutdown_function() after an explicit exit (although its still not running in parallel). – symcbean Sep 04 '18 at 20:06
  • You also need to send an explicit `Connection: close` header and make sure your html is well formed. – symcbean Sep 04 '18 at 20:23
0

If you really, really want to run it in parallel, then you need to run it in a sperate process. That means you are running it in different scope, so while the code you invoke might contain $this->doSomething($member), that "this" won't be this "this".

Assuming that is possible, then your question is a duplicate of this one (but beware - the accepted answer is not good). Note that you will run in blocking problems if both parts of the script depend on a session.

symcbean
  • 47,736
  • 6
  • 59
  • 94