Reputation: 1912
I am trying to send emails using cron tasks with Symfony , so my question is how would I execute my command with using swiftmailer in my execute function ?Thanks in advance
I want the swiftmailer to be in my execute method, so I can send emails based on cron tasks
$mail = \Swift_Message::newInstance();
$mail->setFrom('[email protected]')
->setTo('[email protected]')
->setSubject('Email subject')
->setBody('email body, can be swift template')
$this->get('mailer')->send($mail);
my CronTasksRunCommand
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<comment>Running Cron Tasks...</comment>');
$this->output = $output;
$em = $this->getContainer()->get('doctrine.orm.entity_manager');
$crontasks = $em->getRepository('AppBundle:CronTask')->findAll();
foreach ($crontasks as $crontask) {
// Get the last run time of this task, and calculate when it should run next
$lastrun = $crontask->getLastRun() ? $crontask->getLastRun()->format('U') : 0;
$nextrun = $lastrun + $crontask->getInterval();
// We must run this task if:
// * time() is larger or equal to $nextrun
$run = (time() >= $nextrun);
if ($run) {
$output->writeln(sprintf('Running Cron Task <info>%s</info>', $crontask));
// Set $lastrun for this crontask
$crontask->setLastRun(new \DateTime());
try {
$commands = $crontask->getCommands();
foreach ($commands as $command) {
$output->writeln(sprintf('Executing command <comment>%s</comment>...', $command));
// Run the command
$this->runCommand($command);
}
$output->writeln('<info>SUCCESS</info>');
} catch (\Exception $e) {
$output->writeln('<error>ERROR</error>');
}
// Persist crontask
$em->persist($crontask);
} else {
$output->writeln(sprintf('Skipping Cron Task <info>%s</info>', $crontask));
}
}
// Flush database changes
$em->flush();
$output->writeln('<comment>Done!</comment>');
}
Upvotes: 2
Views: 1766
Reputation: 1899
If your Command class extends ContainerAwareCommand class, then just replace
$this->get('mailer')->send($mail);
with
$this->getContainer()->get('mailer')->send($mail);
Upvotes: 3