4

I'm building a hook_cron in my module but I actually don't want it to run at a maximum of once a day. Is there a Drupal setting for this or do I need to check when the last cron was run and see if that was at least 24 hours ago? How do I do this?

I'm using drupal 7

3 Answers 3

8

I would check the implementation of hook_cron() in the Examples module.

The exact implementation is here, it's pretty straightforward!

Basically, you're setting the next execution time (in the example code as cron_example_next_execution) of your cron run as the very last step in your hook_cron() implementation, and then checking it as the very first thing.

If the variable doesn't exist, then cron will fire off your task, and then set it!

5

This below code will help to run the cron once in a day

function hook_cron() {
$cron_last = variable_get('cron_last');
if ( date('ymd', $cron_last) != date('ymd', time())) {
  //your code here
  variable_set('cron_last', date('ymd', time()));
}  }

variable_get('cron_last') is declared in common.inc

1
  • You should not set the cron_last variable to at date formatted, bud time()
    – user73009
    Commented Dec 9, 2020 at 6:12
3

Have a look at the Elysia Cron Module. This offers you a lot of functionality for crons.

7
  • 1
    The implementation that OP wants is from within their module. I don't think Elysia Cron (although AWESOME) will actually solve this use case.
    – Chapabu
    Commented Feb 15, 2013 at 16:44
  • You're right, but i think the module will anyway help him to control the cron runs ...
    – Lance
    Commented Feb 15, 2013 at 16:48
  • Yes, on a site by site basis, but if OPs module only needs to run it's cron tasks once per day then you shouldn't rely on people having Elysia Cron and then setting it themselves :)
    – Chapabu
    Commented Feb 15, 2013 at 16:54
  • 4
    But you could enforce a dependency on Elysia Cron and implement hook_cronapi() instead...
    – Clive
    Commented Feb 15, 2013 at 16:58
  • 1
    Yep fair point @Chapabu it's just an option, and I guess if this is a custom module and Elysia is already installed it'd be an easier one
    – Clive
    Commented Feb 15, 2013 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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