class Bgtask_Abstract

Class Bgtask_Abstract - an abstract class for implementing background tasks.


abstract class Bgtask_Abstract

{

/*
* Signals
*/

const SIGNAL_SLEEP = 1;

const SIGNAL_CONTINUE = 2;

const SIGNAL_STOP = 3;

/*
* Statuses
*/

const STATUS_UNDEFINED = 0;

const STATUS_RUN = 1;

const STATUS_SLEEP = 2;

const STATUS_STOPED = 3;

const STATUS_FINISHED = 4;

const STATUS_ERROR = 5;

/**
* Builder, receives task settings
* @param array $config
*/

public function __construct(array $config)

/**
* Get task description, an abstract
* method, the logic is to be implemented in the relevant task class,
* returns a description string, like: «Statistics revision»
* @return string
*/

abstract public function getDescription();

/**
* Kill the process
*/

public function terminate()

/**
* Finish the task, task statistics getting updated,
* setting the «Finish» status
*/

public function finish()

/**
* Stop running a task due to an error
* @param string $message - optional
*/

public function error($message = '')

/**
* Record the message to the task log
* @param string $message
*/

public function log($message)

/**
* Stop running a task
*/

public function stop()

/**
* Update the task statistics
* to send the information on the task progress
* @return void
*/

public function updateState()

/**
* Process received signals,
* starts processing signals and arranges for their receival
*/

public function processSignals()

/**
* Run a task, an abstract method
* for describing the task itself
*/

abstract public function run();

/**
* Set up an adapter for logger interface
* @param Bgtask_Log $logger
* @return void
*/

public function setLogger(Bgtask_Log $logger)

/**
*Set the number of expected operations (overall counter)
* @param integer $count
*/

public function setTotalCount($count)

/**
* Set the number of finished operations
* @param integer $count
*/

public function setCompletedCount($count)

/**
* Increase the number of finished operations
* @param integer $count — optional, default = 1
*/

public function incrementCompleted($count = 1)

}

A example of a simplest task:

A cycle of 1000 iterations, every of which lasts for one second

class Task_Test extends Bgtask_Abstract
{
 /**
* (non-PHPdoc)
* @see Bgtask_Abstract::getDescription()
*/
public function getDescription()
{
return 'Test task 1000 slow operations';
}
/**
* (non-PHPdoc)
* @see Bgtask_Abstract::run()
*/
public function run()
{
$this->setTotalCount(1000);
for($i=0;$i<1000;$i++){
sleep(1);
$this->incrementCompleted();
$this->updateState();
$this->processSignals();
}
$this->finish();
}
}

comments powered by Disqus