Skip to content

Instantly share code, notes, and snippets.

@KendallHopkins
Created June 25, 2010 06:42
Show Gist options
  • Save KendallHopkins/452525 to your computer and use it in GitHub Desktop.
Save KendallHopkins/452525 to your computer and use it in GitHub Desktop.
<?php
class MutableEventHeap extends SplMinHeap
{
private $_event_array = array();
function compare( $event1 , $event2 )
{
if( $event1->time > $event2->time )
return -1;
elseif( $event1->time < $event2->time )
return 1;
else
return 0;
}
function setEvent( $key, $unix_timestamp, $callback, $params = array() )
{
if( array_key_exists( $key, $this->_event_array ) )
$this->clearEvent( $key );
$event = new stdClass();
$event->key = $key;
$event->time = $unix_timestamp;
$event->callback = $callback;
$event->params = $params;
$event->is_active = TRUE;
$this->insert( $event );
$this->_event_array[$key] = $event;
}
function clearEvent( $key )
{
if( array_key_exists( $key, $this->_event_array ) ) {
$this->_event_array[$key]->is_active = FALSE;
unset( $this->_event_array[$key] );
}
}
function processEvents()
{
$current_time = microtime( TRUE );
while( $this->valid() && $this->top()->time <= $current_time ) {
$current_job = $this->extract();
if( $current_job->is_active ) {
call_user_func_array( $current_job->callback, $current_job->params );
unset( $this->_event_array[$current_job->key] );
}
}
}
function processUntilEmpty()
{
while( $this->valid() ) {
$time_until_next_event = $this->getTimeUntilNextEvent();
if( $time_until_next_event > 0 )
usleep( $time_until_next_event*1000000 );
$this->processEvents();
}
}
function getTimeUntilNextEvent()
{
return $this->top()->time - microtime( TRUE );
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment