Skip to content
Jason M edited this page May 31, 2017 · 5 revisions

Synopsis

The abstract Daemon class is the entry point for any daemon you want to create. It is a Singleton so only one daemon instance can be used in an application.

User code only has to implement the execute method in order to have a fully working Daemon. Below is an example of a bare bones daemon. You can run this snippet in the root of your application (where composer.json is).

Pressing ^C will exit the daemon.

require __DIR__ . '/vendor/autoload.php';

// needed for signal handling (so ^C will be captured and exit the daemon)
declare(ticks = 1);

class MyDaemon extends \Lifo\Daemon\Daemon
{
    // execute will be called every loop cycle (1 second by default)
    protected function execute()
    {
        $this->log("Daemon Loop %d", $this->getLoopIterations());
    }
}

// run the daemon (`setVerbose` is called so we can see something for the test)
MyDaemon::getInstance()->setVerbose(true)->run();

Expected output from the above example daemon (The header row below was manually added to explain what each column is and you won't see that in the output of the daemon):

                          PARENT   CHILD
TIMESTAMP                 PID      PID   MESSAGE
2017-05-30 15:04:44.7415: 5453     5453: Daemon Loop 1
2017-05-30 15:04:45.7414: 5453     5453: Daemon Loop 2
2017-05-30 15:04:46.7414: 5453     5453: Daemon Loop 3

The output above shows two different PID's. This is because the main daemon process (the parent) and any children Workers or Tasks can also output to the log. When a child emits a log message it's PID will be different than of the parent. This makes it easier to determine what is doing what in a multi-processing daemon.

Configuration

The Daemon has many configuration methods available to change it's behavior. Some examples (not an exhaustive list):

  • setDaemonize(true) - Toggle "daemon" mode (fork into the background) for the main process.
  • setLoopInterval(x) - Change the loop interval.
  • setLogFile('daemon.log') - Set log destination.
  • setAutoRestartInterval(3600) - Set auto-restart.
  • setDebug(true) - Enable debugging mode.
  • setDebugLevel(3) - Set debugging level.
  • ... etc ...

Any custom configuration you want to set must be done before you call the run() method.

Clone this wiki locally