0

I'm working on a D8 project and I want to send every day an automated mail to all users with a specific role, lets say 'custom admin'. The mail should contain the results of a database query.

Rules module is not complete yet so I was thinking to use hook_cron.

Is this the right approach or is there a better way to achieve this?

Thank you in advance for any help/idea.

2 Answers 2

2

Yes! hook_cron is a good approach. Of course, you also will have to set up the server cron, which will trigger the Drupal one. Or at least that's the cleanest solution.

Here you can read how to configure cron.

If you don't use an OS cron to trigger, the following use case may appear. You set the Drupal cron to run each day at 00:00.

But nobody is browsing the site at 00:00. The next user will come at 6:54 in the morning. By the request the cron will know: oh.. it's 6:54, I should have run the cron at 00:00, so I will run it now.

If the subscribed modules have heavy processes on going, the request for the user could be slow. There is your module, which sending emails (not a big deal) but also the Drupal garbage collector (temporary files, abounded fields etc..) may run by this time. If this is the first extra cron hook of your site: don't mind it. It won't change much.

5
  • Thanks! But if I don't set up the server and add a time check in the hook_cron should work fine right? Otherwise how should I set up the server?
    – Ismini
    Sep 8, 2017 at 9:31
  • It will work, but not exactly as expected. I will update my answer.
    – ssibal
    Sep 8, 2017 at 9:32
  • Ok. Thank you so much. That was my concern. I have to process all the nodes of a specific content type (which will be a lot) so I guess the best option is o set up the server as well. Do you have any link how to set up the server?
    – Ismini
    Sep 8, 2017 at 9:44
  • Your welcome! Updated my answer!: )
    – ssibal
    Sep 8, 2017 at 12:41
  • You are welcome, my friend! : ))
    – ssibal
    Sep 8, 2017 at 13:18
1

hook_cron() will be the good option. Fetch the data from the database using some logic, create an email content and send it to the specific user role.

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.