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!');
    }
}
comments powered by Disqus