Spiga

Cron jobs in Zend Framework

by Gabi Solomon

Recently i had to implement a cronjob for a website that was build with zend framework, and to be honest i haven’t done this before. I did some googling and as a lot of times with zend framework there arent to many resources about this topic.

I did find some topics on stackoverflow.com about it ( found out about zend cli proposal wich sounds interesting ) but not really an answer. So i decided to go ahead and try a solution on my own.

I wrote a while ago about my implementation of the bootstrap file and although that doesn’t look to impressive that helped me to build an easy init for the backup files.

So first of all i must tell you that i added a folder in my root folder ( same level with library ) called crons.
In it i added a file called init.php in witch i “start” the zend machine. I only call some methods from the bootstrap class since you don’t really need all the zend machine.

[php]
$time = microtime(true);
$memory = memory_get_usage();

require ‘../application/bootstrap.php’;

Bootstrap::setupEnvironment();

Bootstrap::setupRegistry();
Bootstrap::setupConfiguration();

Bootstrap::setupDatabase();
Bootstrap::setupTranslation();

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]‘;
}
[/php]

As you see i added some extra lines to do some little debugging of the cronjobs.

To add a cronjob you place a file in the crons folder you just created and you just include the init file and then you are on your way to code the cron functionality.

Cheers.

  • http://www.eprogeny.com.au Joel Lignier

    Thanks for posting this. Exactly what I was looking for :)

  • Jacek Lange

    nice piece of work. There's something going on at line 11 I don't get:
    1) the Bootstrap class you've published does not allow parameters to function setupDatabase
    2) Besides, isn't “dissableCache” option misspelled?

    • solomongaby

      thanks for the notice, i modified it :)

  • Carlos

    Can you put a cron php script example that will use the init.php and show something like “Hello World” o rsomething like that?

    This is a half way solution, you should put something complete

    • http://www.gabrielsolomon.ro/ gabi solomon

      @Carlos
      Its as simple as including the init file:
      require ./init.php

      and then doing what ever you want in the cron.

  • Tamrix+gsdesign

    Use memory_get_peak_usage() as the above example just gets the memory at the start and end and subtracting it which doesn't actually mean anything.

  • http://www.findprefab.com/find-prefab-homes/panelized-sip Panelized Homes House

    This post was very nicely written, and it also contains a lot of useful facts.

  • Pingback: Cron jobs in Zend Framework « DBGLORY 4 YOU