Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Creating Daemons with PHP

Creating Daemons with PHP

Michael Cheng

February 26, 2014
Tweet

More Decks by Michael Cheng

Other Decks in Programming

Transcript

  1. Creating
    Daemons with
    PHP
    Persistent background tasks in linux

    View Slide

  2. Long living PHP scripts
    ● Never run them from the browser or from the
    web server.
    ● Browser can time out.
    ● Web server times out.
    ● Solution: Run from the command line on
    the server.

    View Slide

  3. Old Way
    #!/usr/bin/php
    while (true){
    do_epic_long_running_task();
    sleep(1);
    }

    View Slide

  4. The Proper Way
    ● Use PHP Process Control extension.
    ● “... implements the Unix style of process
    creation, program execution, signal handling
    and process termination.”
    ● http://sg2.php.net/pcntl
    ● Example: http://sg2.php.net/manual/en/pcntl.
    example.php

    View Slide

  5. An Easier Way
    ● Use Clio - Lightweight utility and helper
    classes for PHP CLI applications
    ● https://github.com/nramenta/clio
    ● Example:
    ○ https://github.com/CoderKungfu/php-
    queue/tree/master/demo/runners

    View Slide

  6. Making the Daemon Service
    (CentOS/Redhat)
    Add this to the top:
    And run this command:
    #!/usr/bin/php
    #
    # MyAwesomeDaemon Starts the PHP-Queue runner for BlahDaemon
    #
    # chkconfig: - 91 91
    # description: Runner for blah daemon.
    $ chkconfig --levels 235 BeanstalkSampleDaemon on

    View Slide