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');
?>