Here is my problem : I have an application that allows users to synchronize their data with social networks. The problem is that each synchronization can take up to 10 seconds. So I would like to trigger the synchronization in “background” task, and if possible parallelize all synchronisation.
Currently, my script looks like :
$user = user::login($username, $password);
/* Do some treatments, display the home page */
$user->synchronize();
/* END OF LOGIN SCRIPT */
and in my user.class.php, I have something like
public function synchronize(){
$Networks = socialNetworks::getByUserId($this->userid);
foreach($Networks as $n) $n->synchronize();
}
and finally in the socialNetworks.class.php, I have implemented all the synchronization scripts for each social network (fb, linkedin, google+, …).
Note that I don’t need to wait for the result of the synchronization when logging in.
So I have 2 problems here :
- when calling $user->synchronize(); the login script is blocked until the end of the loop
- the loop itself is very long, and I would like to launch parallel “threads”, to make it faster when calling the synchronize() method (I have some Ajax triggering this action).
What would you suggest to optimize this ?
Thanks.
One option is to use Gearman, and offload this work to it’s workers.
You basically create a PHP script that does some work. Then you tell it to do that work from your login script, and the work will be done in the background outside of the request.