If you need to start php cronjobs setting up your whole Zend Framework environment for use is the cronjob scripts is really easy. Just create a new directory cronjobs in your Zend framework project. Create the directory at the same level as the application and public folder. This way the code is not accessible for the web server.
In the cronjobs directory create a init.php file:
<?php
$time = microtime(true);
$memory = memory_get_usage();
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', 'development');
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
register_shutdown_function('__shutdown');
function __shutdown() {
global $time, $memory;
$endTime = microtime(true);
$endMemory = memory_get_usage();
echo '
Time [' . ($endTime - $time) . '] Memory [' . number_format(( $endMemory - $memory) / 1024) . 'Kb]';
}
This will bootstrap the application but not run it. This will start the application in the development environment (APPLICATION_ENV). You can make a cronjob environment in your application.ini if you need special settings. I added some extra information about execution time and memory usage, which might come in handy.
Now your ready to add the real script. Just add the scripts in the cronjobs directory and include the init.php file:
<?php require_once 'init.php'; // The actual script.
Now you can access all namespaced zend framework classes from your project in your scripts.
Tags: cronjob, zend framework
Great! Needed this for a project of mine.
[...] http://www.god-object.com/2010/03/26/bootstrap-zend-framework-for-use-in-cronjobs/ [...]
I really like the idea of adding a simple __shutdown function for all cronjobs, thats q good thing!
[...] Wer für seine Zend Framework Anwendung auch den ein oder anderen CronJob benötigt, sollte einen kurzen Blick auf das Tutorial von God Object werfen, es wird eine ganz gute Bootstrap Methode vorgestellt, die beim Starten von Jobs genutzt werden kann, interessant ist hier die Verwendung der PHP Funktionen um den Speicherverbrauch und Ausführungszeit wiederzugeben (Cronjobs mit Zend Framework) [...]
Simplest and hence fastest solution. Though it could have avoided bootstrapping ‘views’, but for simple cases like mine, it’s perfect!
Thanks mate
Best tut so far i’ve seen! GREAT!
Thank you, it works.