Skip to content

Instantly share code, notes, and snippets.

@elrikdante
Created August 23, 2013 16:23
Show Gist options
  • Save elrikdante/6321245 to your computer and use it in GitHub Desktop.
Save elrikdante/6321245 to your computer and use it in GitHub Desktop.
A Comet implementation in Php. The first callback should be some function that's waiting for an external result, which it will return (otherwise, it should not return anything), the second callback is the function to invoke with the result of the first callback. Thats it.
<?php
define('MESSAGE_POLL_MICROSECONDS', 500000);
define('MESSAGE_TIMEOUT_SECONDS', 60);
define('MESSAGE_TIMEOUT_SECONDS_BUFFER', 5);
class Comet {
public $work;
public $callback;
public static function &init($work, $callback) {
session_write_close();
set_time_limit(MESSAGE_TIMEOUT_SECONDS+MESSAGE_TIMEOUT_SECONDS_BUFFER);
$instance = new self($work,$callback);
return $instance;
}
public function __construct($work,$callback) {
$this->work = $work;
$this->callback = $callback;
}
public function poll() {
$counter = MESSAGE_TIMEOUT_SECONDS;
$data = null;
while($counter > 0) {
if ($data = call_user_func($this->work)) {
break;
} else {
usleep(MESSAGE_POLL_MICROSECONDS);
$counter -= MESSAGE_POLL_MICROSECONDS / 1000000;
}
}
call_user_func_array($this->callback, array($data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment