0

I've created a custom module in drupal and implemented hook_cron. My hook is working perfectly, when I click on run cron button from admin interface.

How can I automatically execute my hook after a specific time interval is passed, without clicking on the Run cron button from the administrative interface?

1

Drupal supports two types of cron jobs:

Poormanscron

This is the default Drupal 7 cron, where at the end of a page request after a certain amount of time, hook_cron is called. This is controlled by the Run cron every ... setting at admin/config/system/cron.

This means that if cron is configured to run every 3 hours, the first user to visit the page after 3 hours will trigger cron. This also means on a low-traffic site that it can many more hours before cron is actually called.

Scheduled cron

This is a much more reliable method which does not involve the user. The principle is that the cron page is called from an external source (usually crontab on the server) at a set interval. As long as the server is up, it will run guaranteed every 3 hours.

In order to enable this, make sure to disable Poormanscron at admin/config/system/cron (set it to run never). And create a cron job (General and Linux manual).

In case of a Windows environemt, one can use Windows' built in scheduled tasks. Please refer to this manual page.

UPDATE Be aware that the manual is a little outdated, since Drupal 7 the cron script is protected by a token (to prevent DDoS). So where you see to call http://www.example.com/cron.php, add your site specific token. This can be found on your site's status page and looks like this: http://www.example.com/cron.php?cron_key=xxxxxxxxxx.

0

Create a Drupal 7 Module. Then add this following function.

function my_sample_module_cron() {
    $sample_module_rule =  60 * 60; //Second * Minute [You can d0 60 * 60 * 2 for running cron in every two hours
    $date = date("Y-m-d H:i:s", time());
    if ((time() - variable_get('sample_module_rule ', 0)) > $sample_module_rule ) { 
        variable_set('sample_module_rule ', time());
        sample_function();
    }
}

Now visit admin/config/system/cron in Administrator Login.

enter image description here

From Run cron every option select the time gap for each cron run. In there you will find option from "One Hour" to "1 Week".

If you need smaller timegap install Ultimate Cron Module - https://www.drupal.org/project/ultimate_cron . Where you will be able to setup Advance Cron settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.