2016-04-13 9 views
1

Ich versuche, E-Mails mit cron Aufgaben mit Symfony zu schicken, so ist meine Frage, wie würde ich mit der Verwendung von Swiftmailer in meiner Funktion ausführen meinen Befehl ausführen? Vielen Dank im VorausE-Mails von cron Aufgaben in symfony Senden

ich will Swiftmailer in meiner ausführen Methode sein, also kann ich E-Mails basierend auf cron Aufgaben

    $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); 

meine 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>'); 
} 

Antwort

2

Wenn Ihre Command Klasse ContainerAware senden erstreckt Command Klasse, dann ersetzen Sie einfach

$this->get('mailer')->send($mail); 

mit

$this->getContainer()->get('mailer')->send($mail);