Reputation: 11
When a certain action happens on the site (built in PHP and MySQL) I would like few asynchronous things to happen on the site.
For example, when a user answers a question, uploads document, I want few asynchronous things to happen in the background such as: 1.update user's score 2. Post a message on Facebook wall 3.track users actions.
What PHP, JavaScript and MySQL technologies are best for achieving this? Please help.
I want something that MySQL triggers but wanted to happen asynchronously.
Upvotes: 1
Views: 2387
Reputation: 11
Use the swoole extension. https://github.com/matyhtf/swoole
asyc mysql example:
$db = new mysqli;
$db->connect('127.0.0.1', 'root', 'root', 'test');
$db->query("show tables", MYSQLI_ASYNC);
swoole_event_add(swoole_get_mysqli_sock($db), function($__db_sock) {
global $db;
$res = $db->reap_async_query();
var_dump($res->fetch_all(MYSQLI_ASSOC));
exit;
});
Upvotes: 1
Reputation: 3382
The best option is to call three separate PHP scripts using exec and passing the output to null, like below.
exec("/usr/bin/php somescript.php >> some_log_file.log 2>&1 &");
Doing the same exec on three scripts for your three functions will execute, all three things concurrently/asynchronously. This is what your after.
If you add jobs to a job queue and then have a cron clear that queue, your not really doing it asynchronously. Your still doing things one by one, in a synchronous blocking fashion - although the user is not waiting for these things to happen. There might be a delay in the queue being cleared as well if your site has high traffic, you won't get the same delay with exec. Since the script will be executed immediately and concurrently to the initial request.
Side Note: This is why Node.js is becoming so popular it's built on JavaScript which is designed for this kind of development approach. Asynchronous and event driven.
Upvotes: 2
Reputation: 439
also you can use php system call to run another program in background: http://php.net/manual/en/function.system.php
Upvotes: 0
Reputation: 8700
The only two options I can think of are a messaging queue, and async ajax.
The first option works by putting jobs into a database, then a scheduled php program will loop through every job in the database and run them.
The second is just calling a php program using ajax.
For the first option look at something like: http://alanstorm.com/simple_php_job_queue
For the second look at jquery, and its ajax options: http://api.jquery.com/jQuery.ajax/
Upvotes: 2