Drupal – Define Your Own Cron Job

How does the cron job in Drupal work? Let’s take a look.
cron.php

<?php
// $Id: cron.php,v 1.36 2006/08/09 07:42:55 dries Exp $

/**
 * @file
 * Handles incoming requests to fire off regularly-scheduled tasks (cron jobs).
 */

include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_cron_run();

 

Looks simple, right? the drupal_cron_run() function will run the default Drupal cron tasks as well as invoking the hook_cron() in all modules.

If you want to schedule you own tasks but skipping those of Drupal, then you could just copy the cron.php and add your own tasks in it. For example, you could call a module function. In a custom module, i have a function called custom_my_own_cron().
custom.module

...
function custom_my_own_cron() {
	print 'I am executed with my own cron job';
}
...

 

Add this function in my-own-cron.php.

<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Skip the default Drupal cron tasks and those hook_cron() functions
//drupal_cron_run();

// Do whatever you want here
include_once './includes/module.inc';
if (module_exists('custom') && function_exists('custom_my_own_cron')) {
	custom_my_own_cron();
} else {
	print "my-own-cron.php failed.";
}

 

Open a browser and go to http://<drupal_root>/my-own-cron.php, you should get the printed string. So now you can schedule the my-own-cron.php in crontab just like what we did in the last post.
Drupal – Add Task to the Drupal Cron Job

Done =)

Reference: Drupal Community & Support – Call a function from another module

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.