0

In drupal we have a hook_cron() which runs on cron.

But in cron job we have to specify a path, the cron will access that path and will run the code in the page callback function of that path.

So my question is that why then we need hook_cron() if we can do this by creating path using hook_menu with a page callback and use that path in the cronjob?

Can someone explain this to me?

2

Using hook_cron() Drupal can run all the cron tasks using a single entry point (http://your.site/cron.php) and bootstrap code that is very specific for cron tasks, different from the normal bootstrap code used from Drupal.
This simplifies handling cron tasks since only a single URL is necessary to run them, and the code that runs them is faster compared to the normal code.

If I had the need to run groups of cron tasks at different times, then I could create different cron.php files to execute those specific groups. I would not implement different routes for executing cron tasks for the same reason Drupal 7 doesn't: The code that runs the routes is more complex than the code running the cron tasks and involves more hooks being invoked.
At least that was the reason for doing so when Drupal 7 was first released. With PHP 7, that is probably not a reason enough to prefer custom bootstrapping code to a route handler. As for Drupal 8, cron tasks are executed from a controller associated with a route.

In short, normally cron.php is enough, but it is also rare to even need a different route handler/controller for each cron task modules could.

| improve this answer | |

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.