-
Notifications
You must be signed in to change notification settings - Fork 15
Tasks
Tasks are simple callbacks that perform some sort of job in a forked child process. When you run a task your code is not blocked and will continue running while the task runs in the background. One example might be a task that sends an email out to 1 or more recipients.
Tasks do not return anything to the parent Daemon process.
To start a task, you call Daemon::task($task, [$arg1, $arg2, ...])
with one of the task types below.
- A Closure:
function(){...}
- A callable:
[$myObject, 'methodName']
- An object instance that implements
TaskInterface
:new MyTask()
- A FQCN string:
'Lifo\Daemon\Task\SimpleTask'
. The class will be instantiated within the forked process. This is an important distinction. Since the class is instantiated in the child the parent process doesn't use up any extra memory.
Any extra arguments given to Daemon::task($task, [$arg1, $arg2, ...])
will be passed to the Task::run()
or the Task Closure. However, If you use Closure's you don't really need to pass arguments to the task, instead you can just use use
. Use whichever makes more sense for your code.
// passing arguments to Closures
$this->task(function() use ($arg1, $arg2) {});
// or
$this->task(function($arg1, $arg2) {}, $arg1, $arg2);
// passing arguments to objects.
$this->task(new MyTask(), $arg1, $arg2);
// or
$this->task(new MyTask($arg1, $arg2));
Remember that tasks are not cheap. Every time a task is run a new background process
is started, with a copy of the memory footprint of your parent process. It then has to be reaped and memory reclaimed. If you're starting lots of tasks every loop cycle you may notice degradation of your daemon. Plan your tasks appropriately. Sometimes, instead of lots of little tasks, maybe group logic into bigger tasks that do more.
...
public function execute() {
$this->task(function() {
sleep(3);
$this->log("Hey look!! I'm logging from inside a task");
});
}
...
...
public function execute() {
$this->task([$this, 'doTask']));
}
public function doTask() {
sleep(3);
$this->log("Hey look!! I'm logging from inside a callable");
}
...
...
public function execute() {
$this->task(new MyTask());
// or
$this->task('MyTask');
}
...
class MyTask() implements Lifo\Daemon\Task\TaskInterface {
public function run() {
sleep(3);
$this->log("Hey look!! I'm logging from inside a class");
}
public function getGroup() {}
public function setup() {}
public function teardown() {}
}