I have my plugin working now so that I can email users who's accounts will expire in 7 days time. The users are being selected correctly and the emails are being sent as expected. However, the tasks don't seem to be running in the background. I was expecting that when I hit the controller the task will be triggered and the page would immediately return saying "emails sent". Instead it seems it waits until the emails are sent before returning "emails sent". I'm worried that if the number of emails is large the page will timeout before it completes. It was my understanding that tasks run as a background process but may I have miss understood. Can anyone explain them to me in more detail?
For reference here is the controller and the service of my plugin:
class AcmeNotifications_NotificationsController extends BaseController
{
// let anyone run the controller actions
protected $allowAnonymous = array('actionSendEmail');
public function actionSendEmail()
{
craft()->acmeNotifications_notifications->sendReminderEmail();
//Make sure we kick the task off
if (!craft()->tasks->isTaskRunning())
{
$task = craft()->tasks->getNextPendingTask();
if ($task)
{
craft()->tasks->runPendingTasks();
}
}
craft()->end();
}
}
and:
class AcmeNotifications_NotificationsService extends BaseApplicationComponent
{
public function sendReminderEmail()
{
//Get all users whos account will expire in 7 days
$user_criteria = craft()->elements->getCriteria(ElementType::User);
$user_criteria->userExpiryDate = date('Y-m-d',strtotime("+7 days"));
$users = $user_criteria->find();
if($users){
//Create array of user email addresses
$user_emails = array();
foreach ($users as $user) {
$user_emails[] = array("to" => $user->email);
}
//Create an EmailModel
$email = new EmailModel;
//Set the global attributes
$email->fromName = 'Joe Blogs';
$email->fromEmail = '[email protected]';
$email->subject = 'Your account will expire in 7 days';
$email->htmlBody = 'The message';
//Create the RecipientsModel and add the user emails
$recipients = new Mailer_RecipientsModel();
$recipients->recipients = $user_emails;
if( $recipients->validate()){
//Create mailer task
craft()->mailer_main->newMailer($recipients, $email);
}
echo "emails sent";
}
else{
echo "no emails to send";
}
}
}