Cron Job Script in Zend Framework

To create a cron job script in Zend Framework, we just need 3 steps :

 

1. Create a new directory called “scripts” which is the storage of all the scripts(.sh, .php, etc.).

 

2. Copy public/index.php into “scripts” and rename it to your cron job name, for example “cron.php”.

 

 

3. Modify the code. Instead running the application, we now only do the bootstrap:

 

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

date_default_timezone_set('America/New_York');

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

// only do bootstrap
//$application->bootstrap()->run();
$application->bootstrap();

// get the options and run CLI
try {
    $opts = new Zend_Console_Getopt('abc:');
    if (isset($opts->a)) {
        echo "I got the a option.\n";
    }
    if (isset($opts->b)) {
        echo "I got the b option.\n";
    }
    if (isset($opts->c)) {
        echo "I got the c option.\n";
    }
} catch (Zend_Console_Getopt_Exception $e) {
    echo $e->getUsageMessage();
    exit;
} catch (exception $e) {
    echo $e->getMessage();
    exit;
}
Posted in Zend Framework | Tagged , | 1 Comment
  1. Hi, great post. Thanks a lot for this help.

    If I may ask: How we can set the SERVER_Name in this file?

    Thanks