Home » Send Email with Cronjob in Cakephp 3.x
CakePHP

Send Email with Cronjob in Cakephp 3.x

Easily Set Cron job with cakephp 3.x

A Cron job is a task that is run based on time interval , we just need to set cron job from our cpanel and it will run automatically backend side . We can run cron job every minute , every hour, every day or every month based on our requirement.

In cakephp 3.x to set a cron job please follow the below simple steps

First we need to create a php file on webroot so we can run our controller action as php file in cronjob

Create a file cron.php in webroot folder (location – YourProject/webroot/cron.php) and paste the following code

Cron.php

<?php

$_SERVER[ 'HTTP_HOST' ] = 'yourdomain.com'; //  use only domain name here
require dirname(__DIR__) . '/config/bootstrap.php';
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\Routing\Router;
use Cake\Routing\DispatcherFactory;

if(PHP_SAPI == "cli" && $argc == 2) {
  
  $dispatcher = DispatcherFactory::create();
  $request = new Request($argv[1]);
    $request = $request->addParams(
        Router::parse(
            $request->url,
            ''
        )
    );
    $dispatcher->dispatch(
      $request,
      new Response()
  );
}
else {
  exit;
}

?>

Now we need to create a controller and action for our cronjob(location: /yourProject/src/Controller/CronController.php

<?php

namespace App\Controller;

use App\Controller\AppController;
use Cake\Mailer\Email;

/**
 * Cron Controller
 *
 *
 * @method \App\Model\Entity\Cron[] paginate($object = null, array $settings = [])
 */
class CronController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Http\Response|void
     */
    public function initialize()
    {
        parent::initialize();
        $this->Auth->allow();
        $this->loadModel('Reminder');
    }


    public function index()
    {
        $today = date("m/d/Y");
        $cron = $this->Reminder->find('all', ['conditions' => ['reminder_date' => $today, 'status' => 0]]);
        foreach ($cron as $key => $value) {
            $userEmail = $value->user_email;

            $email = new Email('default');
            $email->from(['me@example.com' => 'My Site'])
                ->transport('gmail')
                ->to($userEmail)
                ->subject('About')
                ->send('My message');

            //if you want to run query then you can do like this
            //  $updateActivate  = $this->Reminder->updateAll(['status'=> 1], ['id'=> $reminderId]);
        }
        $this->set(compact('cron'));
        $this->set('_serialize', ['cron']);
    }
}
?>

Now our cakephp work is finished . now open your cpanel and click on cron job icon that is showing in below image.

cron1

Now fill time for your cakephp cronjob file . below image contains a cronjob example that will run every minute

cron2

and in command enter your file location

Syntax

/usr/local/bin/php/home/servername/public_html/projectName/webroot/cron.php /controllerName/ActionName 

Example

/usr/local/bin/php/home/webserver/public_html/cakephp/webroot/cron.php /cron/index

Now click on Add New Cron Job button that will save your cron file

Your cron is successfully run in backend  and if not working then you can check errors in error.log file .

Tags

3 Comments

Click here to post a comment

84 − 74 =

  • you should create inside src\shell and format send mail

    $email = new Email();
    $email
    ->setEmailFormat(‘html’)
    ->setTo($email)
    ->setFrom($your_email)
    ->setSubject($subject)
    ->send($content);

  • Calling the summit a milestone for bilateral strategic partnership, ASEAN leaders said that it is in the interests of both sides to safeguard multilateralism as well as free trade and that ASEAN is ready to align its development strategies with the Belt as well as Road Initiative as well as open up more space for cooperation. Jarred Dreyfuss

  • I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade website post from you in the upcoming as well. Actually your creative writing abilities has inspired me to get my own website now. Really the blogging is spreading its wings quickly. Your write up is a great example of it. Andreas Bigby