Setting up cron jobs in Magento

Magento has a powerful built-in engine to perform cronjobs, let’s see how we make them work.

First of all, we need to declare a crontab in our OS. Let’s say we have Ubuntu ( or derived, or Debian ) and we want to run magento cronjobs every minute:

1
crontab -e

adding the line which defines that our jobs need to be scheduled for every single minute of the day:

1
2
# * * * * * path/to/php/binaries /path/to/magento/cron.php
* * * * * /usr/bin/php /var/www/magento/cron.php

So our environment in running Magento’s cron script every minute, but our script produces nothing: let’s do something!

Let’s say that we developed a custom module, useful for sysadmins and similar, which has a table containing the references of all our development team ( name, position, email, .. ) and we regularly want to inform our team that Magento is running properly.

So let’s modify the XML of our module, in app/code/local/MyCompany/MyModule/etc/config.xml adding the crontab reference:

1
2
3
4
5
6
7
8
9
10
11
12
<config>
...
    <crontab>
        <jobs>
            <mymodule_apply_all>
                <schedule><cron_expr>* * * * *</cron_expr></schedule>
                <run><model>mymodule/modelName::modelMethod</model></run>
            </mymodule_apply_all>
        </jobs>
    </crontab>
...
</config>

So, you see that in the example above you need to edit everything between tags with:

So now you have to create your method:

app/code/local/MyCompany/MyModule/Model/modelName.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php

public function notifyTeamEverithingIsOk() {
    ...stuff...
    ...stuff...
    ...stuff...

    $sysadmin = Mage::getModel('mymodule/mymodel')->getCollection();

    // the following code is for fun purpose at all, I hope you don't code this way! ;-)

    foreach($sysadmin as $poor_fella){
        mail($poor_fella->getEmail(), 'Nightly report', 'Hey fella, everything's fine!');
    }
}

Hi there! I recently wrote an ebook on web application security, currently sold on leanpub, the Amazon Kindle store and gumroad.

It contains 160+ pages of content dedicated to securing web applications and improving your security awareness when building web apps, with chapters ranging from explaining how to secure HTTP cookies with the right flags to understanding why it is important to consider joining a bug bounty program.

Feel free to skim through some of the free chapters published on this blog and, if the content seems interesting enough to you, grab a copy on leanpub, the Amazon Kindle store, gumroad or simply checkout right down below!

Buy the Web Application Security ebook for $6.99

In the mood for some more reading?

...or check the archives.