public function execute() {
        global $DB, $PAGE;

        // Get the maximum id we are going to use.
        // We use this as records may be added to the table while this task runs.
        $this->maxid = $DB->get_field_sql("SELECT MAX(id) FROM {message_email_messages}");

        // We are going to send these emails from 'noreplyaddress'.
        $noreplyuser = \core_user::get_noreply_user();

        // The renderers used for sending emails.
        $htmlrenderer = $PAGE->get_renderer('message_email', 'email', 'htmlemail');
        $textrenderer = $PAGE->get_renderer('message_email', 'email', 'textemail');

        // Keep track of which emails failed to send.
        $users = $this->get_unique_users();
        foreach ($users as $user) {
            cron_setup_user($user);

            $hascontent = false;
            $renderable = new \message_email\output\email_digest($user);
            $conversations = $this->get_conversations_for_user($user->id);
            foreach ($conversations as $conversation) {
                $renderable->add_conversation($conversation);
                $messages = $this->get_users_messages_for_conversation($conversation->id, $user->id);
                if ($messages->valid()) {
                    $hascontent = true;
                    foreach ($messages as $message) {
                        $renderable->add_message($message);
                    }
                }
                $messages->close();
            }
            $conversations->close();
            if ($hascontent) {
                $subject = get_string('emaildigestsubject', 'message_email');
                $message = $textrenderer->render($renderable);
                $messagehtml = $htmlrenderer->render($renderable);
                if (email_to_user($user, $noreplyuser, $subject, $message, $messagehtml)) {
                    $DB->delete_records_select('message_email_messages', 'useridto = ? AND id <= ?', [$user->id, $this->maxid]);
                }
            }
        }
        cron_setup_user();
        $users->close();
    }