使用cron作业触发URL

时间:2017-03-07 08:58:45

标签: cron symfony ovh

我正在使用Symfony 3网站,我需要通过cron作业调用我网站的网址。

我的网站托管在OVH,我可以配置我的cron作业。

目前,我已设置命令:./demo/Becowo/batch/emailNewUser.php

emailNewUser.php内容:

<?php

header("Location: https://demo.becowo.com/email/newusers");

?>

在日志中我有:

  

[2017-03-07 08:08:04] ## OVH ## END - 2017-03-07 08:08:04.448008 exitcode:0

     

[2017-03-07 09:08:03] ## OVH ## START - 2017-03-07 09:08:03.988105执行:/usr/local/php5.6/bin/php /homez.2332 / coworkinwq /./演示/ Becowo /批次/ emailNewUser.php

但是不发送电子邮件。 我应该如何配置我的cron作业来执行此URL? 或者我应该直接拨打我的控制器?怎么样?

2 个答案:

答案 0 :(得分:1)

好的,终于可行了!!!

以下是我为其他人采取的步骤:

1 /您需要一个控制器来发送电子邮件:

由于控制器将通过命令调用,您需要注入一些服务

em:用于刷新数据的实体管理器

邮件:访问swiftMailer服务以发送电子邮件

模板:访问TWIG服务以使用电子邮件正文中的模板

MemberController.php

&#13;
&#13;
<?php

namespace Becowo\MemberBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Becowo\CoreBundle\Form\Type\ContactType;
use Becowo\CoreBundle\Entity\Contact;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class MemberController extends Controller
{
  private $em = null;
  private $mailer = null;
  private $templating = null;
  private $appMember = null;

  public function __construct(EntityManager $em, $mailer, EngineInterface $templating, $appMember)
  {
      $this->em = $em;
      $this->mailer = $mailer;
      $this->templating = $templating;
      $this->appMember = $appMember;
  }

 

  public function sendEmailToNewUsersAction()
  {
    // To call this method, use the command declared in Becowo\CronBundle\Command\EmailNewUserCommand 
    // php bin/console app:send-email-new-users

  	$members = $this->appMember->getMembersHasNotReceivedMailNewUser();
  	$nbMembers = 0;
  	$nbEmails = 0;
  	$listEmails = "";
    
  	foreach ($members as $member) {
  		$nbMembers++;
  		if($member->getEmail() !== null)
  		{
  			$message = \Swift_Message::newInstance()
	        ->setSubject("Hello")
	        ->setFrom(array('toto@xxx.com' => 'Contact Becowo'))
	        ->setTo($member->getEmail())
          ->setContentType("text/html")
	        ->setBody(
	            $this->templating->render(
	                'CommonViews/Mail/NewMember.html.twig',
	                array('member' => $member)
	            ))
          ;

	      	$this->mailer->send($message);
	      	$nbEmails++;
	      	$listEmails = $listEmails . "\n" . $member->getEmail() ;

	      	$member->setHasReceivedEmailNewUser(true);
	      	
	  		$this->em->persist($member);
  		}
  	}
      $this->em->flush();

  	$result = " Nombre de nouveaux membres : " . $nbMembers . "\n Nombre d'emails envoyes : " . $nbEmails . "\n Liste des emails : " . $listEmails ;
    

  	return $result;
  }

}
&#13;
&#13;
&#13;

2 /将控制器称为服务

应用程序/配置/ services.yml

&#13;
&#13;
  app.member.sendEmailNewUsers :
        class: Becowo\MemberBundle\Controller\MemberController
        arguments: ['@doctrine.orm.entity_manager', '@mailer', '@templating', '@app.member'] 
&#13;
&#13;
&#13;

3 /创建控制台命令以调用控制器

Doc:http://symfony.com/doc/current/console.html

YourBundle /命令/ EmailNewUserCommand.php

&#13;
&#13;
<?php

namespace Becowo\CronBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class EmailNewUserCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        
        // the name of the command (the part after "php bin/console")
        $this->setName('app:send-email-new-users')
			 ->setDescription('Send welcome emails to new users') 
    	;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	// outputs a message to the console followed by a "\n"
        $output->writeln('Debut de la commande d\'envoi d\'emails');

     	// access the container using getContainer()
        $memberService = $this->getContainer()->get('app.member.sendEmailNewUsers');
        $results = $memberService->sendEmailToNewUsersAction();

        $output->writeln($results);
    }
}
&#13;
&#13;
&#13;

4 /测试你的命令!

在控制台中,调用命令:php bin/console app:send-email-new-users

5 /创建一个脚本来运行命令

Doc(法语):http://www.christophe-meneses.fr/article/deployer-son-projet-symfony-sur-un-hebergement-perso-ovh

..网络/批次/ EmailNewUsers.sh

&#13;
&#13;
#!/bin/bash

today=$(date +"%Y-%m-%d-%H")
/usr/local/php5.6/bin/php /homez.1111/coworkinwq/./demo/toto/bin/console app:send-email-new-users --env=demo > /homez.1111/coworkinwq/./demo/toto/var/logs/Cron/emailNewUsers-$today.txt
&#13;
&#13;
&#13;

我花了一些时间才能得到正确的剧本。

照顾php5.6:它必须与OVH上的PHP版本相匹配

不要忘记在服务器上上传bin / console文件

homez.xxxx / name必须与你的配置匹配(我在OVH上找到了我的,然后在日志中找到了)

重要提示:在服务器上传文件时,请添加执行权限(CHMOD 704)

6 /在OVH中创建cron作业

使用以下命令调用脚本:./demo/Becowo/web/Batch/EmailNewUsers.sh

语言:其他

7 /等等!

您需要等待下一次运行。然后查看OVH cron日志,或者查看通过.sh文件中的命令创建的自己的日志

我花了好几天才得到它.. 享受!!

答案 1 :(得分:0)

如上所述,您应该使用symfony commaad。这是一个例子。

注意:虽然它有效,但您始终可以改进此示例。特别是way命令调用你的端点。

控制器服务定义:

services:
    yow_application.controller.default:
        class: yow\ApplicationBundle\Controller\DefaultController

控制器本身

namespace yow\ApplicationBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("", service="yow_application.controller.default")
 */
class DefaultController
{
    /**
     * @Method({"GET"})
     * @Route("/plain", name="plain_response")
     *
     * @return Response
     */
    public function plainResponseAction()
    {
        return new Response('This is a plain response!');
    }
}

命令服务定义

services:
    yow_application.command.email_users:
        class: yow\ApplicationBundle\Command\EmailUsersCommand
        arguments:
            - '@http_kernel'
        tags:
            - { name: console.command }

命令本身

namespace yow\ApplicationBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class EmailUsersCommand extends Command
{
    private $httpKernel;

    public function __construct(HttpKernelInterface $httpKernel)
    {
        parent::__construct();

        $this->httpKernel = $httpKernel;
    }

    protected function configure()
    {
        $this->setName('email:users')->setDescription('Emails users');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $request = new Request();
        $attributes = [
            '_controller' => 'yow_application.controller.default:plainResponseAction',
            'request' => $request
        ];
        $subRequest = $request->duplicate([], null, $attributes);

        $response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

        $output->writeln($response);
    }
}

<强>测试

$ php bin/console email:users
Cache-Control:      no-cache, private
X-Debug-Token:      99d025
X-Debug-Token-Link: /_profiler/99d025

This is a plain response!
1.0
200
OK