Sometimes things need to be done without user interaction – for example, database optimisation or log rotation.
For this, Elgg has a cron endpoint.
Cron is a unix tool which executes commands at a specific time of day (other operating systems have similar tools). This keys off a file called a crontab – an example is given file is included and called crontab.example
.
The crontab calls simplified yet powerful cron endpoint – http://yoursite/pg/cron/PERIOD
, where PERIOD is one of the following:
- reboot – Execute on system reboot
- minute – Execute every minute
- fiveminute – Execute every five minutes
- fifteenmin – Execute every fifteen minutes
- halfhour – Execute every half hour
- hourly – Execute once every hour
- daily – Execute every day
- weekly – Execute weekly
- monthly – Execute once a month
- yearly – Execute every year
When these endpoints are triggered by your crontab a plugin hook is triggered. To make use of this, register a plugin hook as follows:
register_plugin_hook('cron', PERIOD, 'my_cron_handler');
Where PERIOD is one of the key words listed above. Here is some sample code using Cron – in this case it is taken from the system log rotation module I added to SVN today.
<?php
/**
* Elgg log rotator.
*
* @package ElggLogRotate
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
* @author Curverider Ltd
* @copyright Curverider Ltd 2008
* @link http://elgg.com/
*/
/**
* Initialise the plugin.
*
*/
function logrotate_init()
{
$period = get_plugin_setting('period','logrotate');
switch ($period)
{
case 'weekly':
case 'monthly' :
case 'yearly' :
break;
default: $period = 'monthly';
}
// Register cron hook
register_plugin_hook('cron', $period, 'logrotate_cron');
}
/**
* Trigger the log rotation.
*
*/
function logrotate_cron($hook, $entity_type, $returnvalue, $params)
{
$resulttext = elgg_echo("logrotate:logrotated");
if (!archive_log())
$resulttext = elgg_echo("logrotate:lognotrotated");
return $returnvalue . $resulttext;
}
// Initialise plugin
register_elgg_event_handler('init','system','logrotate_init');
?>
So for get logrotate you MUST to configure a cron entry on your hosting site, right?
Hi Diego,
At the moment yes you must, however the crontab does not need to be installed as a privileged user.
Marcus
OK, Thanks for the help here. I’m still confused. I can not seem to get a cronjob to work. I ‘m trying to get my garbage collector and logrotate working but to no avail I can not get them going?
Do I place, for instance the code above in the crontab.example file or do I have to put the above code in the plug in file?
The code here is to show you how you might write code to use the cron events.
If you just want to run the GC etc then you need to install the cron script from crontab.example.
Type man 5 crontab for more details.