使用cron作业触发URL [英] Trigger an URL with a cron job

查看:105
本文介绍了使用cron作业触发URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony 3网站,我需要使用cron作业来调用我网站的URL.

I'm working on a Symfony 3 website and I need to call a URL of my website with a cron job.

我的网站托管在OVH上,可以在其中配置我的cron作业.

My website is hosted on OVH where I can configure my cron job.

现在,我已经设置了命令:./demo/Becowo/batch/emailNewUser.php

For now, I have setup the command : ./demo/Becowo/batch/emailNewUser.php

emailNewUser.php内容:

emailNewUser.php content :

<?php

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

?>

在日志中,我有:

[2017-03-07 08:08:04] ## OVH ##结束-2017-03-07 08:08:04.448008退出代码:0

[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/./demo/Becowo/batch/emailNewUser.php

[2017-03-07 09:08:03] ## OVH ## START - 2017-03-07 09:08:03.988105 executing: /usr/local/php5.6/bin/php /homez.2332/coworkinwq/./demo/Becowo/batch/emailNewUser.php

但是不会发送电子邮件. 我应该如何配置我的cron作业以执行此URL? 还是我应该直接致电我的控制器?怎么样?

But emails are not sent. How should I configure my cron job to execute this URL ? Or should I call directly my controller ? How ?

推荐答案

好的,终于可以了!!!

ok, finally it works !!!

这是我为他人采取的步骤:

Here are the step I followed for others :

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

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

As the controller will be called via command, you need to injec some services

em:实体管理器刷新数据

em : entity manager to flush data

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

mailer : to access swiftMailer service to send the email

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

templating : to access TWIG service to use template in the email body

MemberController.php

MemberController.php

<?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;
  }

}

2/将您的控制器称为服务

app/config/services.yml

app/config/services.yml

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

3/创建一个控制台命令来调用您的控制器

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

YourBundle/Command/EmailNewUserCommand.php

YourBundle/Command/EmailNewUserCommand.php

<?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);
    }
}

4/测试您的命令!

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

In the console, call you command : php bin/console app:send-email-new-users

5/创建脚本以运行命令

文档(法语): .. Web/Batch/EmailNewUsers.sh

..Web/Batch/EmailNewUsers.sh

#!/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

在这里我花了一些时间来获取正确的脚本.

Here it took me some time to get the correct script.

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

Take care of php5.6 : it has to match your PHP version on OVH

别忘了在服务器上上传bin/console文件

Don't forget to upload bin/console file on the server

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

homez.xxxx/name has to match with your config (I found mine on OVH, and then in the logs)

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

IMPORTANT : when you upload the file on the server, add execute right (CHMOD 704)

6/在OVH中创建cron作业

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

Call your script with the command : ./demo/Becowo/web/Batch/EmailNewUsers.sh

语言:其他

7/等待!

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

You need to wait for the next run. Then have a look on OVH cron logs, or on your own logs created via the command in the .sh file

我花了几天时间才得到它. 享受吧!

It took me several days to get it.. Enjoy !!

这篇关于使用cron作业触发URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆