Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active April 15, 2020 09:42
Show Gist options
  • Save nezarfadle/f9c1f00ca6a1e6c9a7d2315de87f17a4 to your computer and use it in GitHub Desktop.
Save nezarfadle/f9c1f00ca6a1e6c9a7d2315de87f17a4 to your computer and use it in GitHub Desktop.
class Scheduler
{

	protected $actions = [];

	function invoke( $func, $deadline )
	{
		$this->actions[] = [ "deadline" => $deadline, "func" => $func ];
	}

	function run()
	{
		
		while( $this->actions )
		{
			
			$action = array_shift( $this->actions ); // Pull an action to be executed
			$deadline = $action["deadline"];
			$func = $action["func"];
			
			$delta = $deadline - time();

			if( $delta <= 0 )
				$func(); // Execute the action
			else
				// Reschedule the action if its deadline still in the feature
				$this->actions[] = [ "deadline" => $deadline, "func" => $func ];
			
			sleep(1);
			
		}
		
	}	
}

function feature( $msg )
{
	echo $msg;
}


$scheduler = new Scheduler();


$msg = "This content is scheduled to be executed in the feature after 7 Seconds\r\n";
$scheduler->invoke( fn() => feature( $msg ), time() + 7 ); // This feature function will be called after 7 seconds

$msg = "This content is scheduled to be executed in the feature after 2 Seconds\r\n";
$scheduler->invoke( fn() => feature( $msg ), time() + 2 ); // This feature function will be called after 4 seconds

$scheduler->run();

How to run

  1. PHP >= 7.4 ( Because I have used the Arrow Functions which can be replaced by a Closure, so you can use any PHP version supports it )
  2. Save the code in a file named scheduler.php ( this could be any file name ).
  3. From your terminal:
php scheduler.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment