I want to use batch in POST in rest endpoints in Drupal 8, but my batch is not getting progressed. I am creating rest endpoints for my module which will send email to bulk users. So for this purpose I need to use batch which will send email to all users without giving time out error. Please help.
my source code is:
class BatchController {
public static function callBatch() {
$batch = array(
'title' => t('Sending ...'),
'operations' => [],
'init_message' => t('Sending is starting.'),
'finished' => '\Drupal\module_mail\sendEmails::sendEmailsItemCallback',
);
$subject='hello';
$body='body';
$data = array(0 => array('id'=>1,'Fullname'=>"joy", 'Email'=>"[email protected]")
);
foreach($data as $row) {
$batch['operations'][] = ['\Drupal\module_mail\sendEmails::sendEmailsUserItem',[$row,$subject,$body]];
}
batch_set($batch);
return batch_process('home');
}
}
namespace Drupal\module_mail;
class sendEmails {
public static function sendEmailsUserItem($user, $subject, $body, &$context)
{
$message = 'Sending emails';
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'module_mail';
$key = '';
$to= $user['Email'];
$params['email_body'] = $body;
$params['email_subject'] = $subject;
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
}
//batch completed
public static function sendEmailsItemCallback($success, $results, $operations)
{
if ($success) {
$message = \Drupal::translation()->formatPlural(
count($results),
'sent.',
'Emails sent succesfully'
);
}
else {
$message = t('Finished with an error.');
}
drupal_set_message('Sent succesfully');
}
}