Skip to main content

Cakephp 3x Send Email with Cronjob

Cakephp 3.x - Send Email with Cronjob


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]);
            }
        }
        //pr($value);die;
        $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.



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



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 .


Note : 
Please add this line in app/bootstrap.php to autoload router config.

 
// Use composer to load the autoloader. require ROOT . DS . 'vendor' . DS . 'autoload.php';  
 




Other Links

Cron Job with PHP
Send Email through Cronjob in cakephp 3.x
Cakephp 3.x cronjob
Run Cronjob in cakephp 3.x
Run Controllers action in cronjob Cakephp 3.x

Comments

  1. As stated by Stanford Medical, It is really the ONLY reason this country's women live 10 years longer and weigh an average of 19 kilos lighter than us.

    (And really, it has NOTHING to do with genetics or some hard exercise and EVERYTHING about "how" they are eating.)

    BTW, I said "HOW", not "what"...

    Tap this link to reveal if this easy questionnaire can help you discover your true weight loss possibilities

    ReplyDelete
  2. اما ممکن است این سوال به ذهنتان بیاید که یک خرید هاست خرید هاست اشتراکی ارزان ارزان چه هاستی است و چه ویژگی هایی باید دارا باشد در ادامه مقاله قصد داریم ویژگی های هاست ارزان را خرید هاست لینوکس ماهانه معرفی کنیم و در آخر به معرفی بهترین هاست ایران از میان هاستینگ های برتر کشور بپردازیم .اگر قصد راه اندازی یک سایت باکیفیت و پر بازدید را دارید حتما باید نکته هایی را رعایت نمایید قسمت سخت افزار از انتخاب ها تشکیل می شود و مناسب برای سایت هست که به سرور استفاده شده با هاست ارزان برای وردپرس سی پی یو ، رم و استفاده از دیگر سخت افزارها هاست ارزان خارجی با ویژگی های عنوان شده مربوط می شود .نرم افراز به دو بخش جدا تقسیم می شود که بخشی از آن به هاست و سرور مربوط هست و بخش دیگر به سیستم مدیریت محتوا سایت شما بستگی دارد .و در نهایت بخش محتوا هاست پرسرعت ارزان ارتباط با کار سئو و بهینه سازی سایت برای موتورهای جستجو و هم چنین بازاریابی از طریق محتوا است .در حقیقت هاست یک بستر الکترونیکی هست که محتویات و مطالب سایت شما داخل آن ذخیره خواهد شد .و این محتویات هاست ارزان قیمت همان فایل و دیتابیس شما است که از طریق اتصال اینترنتی کاربران به سرور در دسترس خواهد بود .لازم است که هاست و دامنه به یک دیگر متصل باشند که این فرآیند از طریق Name server صورت می گیرد .بدین ترتیب اولین کاری که بعد از خرید هاست از شرکت های معتبر هاستینگ باید انجام دهید این هست که نیم سرور های هاست را بر روی دامنه خودتان ست کنید تا نهایتا بعد از گذشت ۷۲ ساعت هاست و دامنه به هم دیگر متصل شوند

    ReplyDelete
  3. I have tried this code i got below error
    Fatal error: Uncaught Error: Class 'Cake\Routing\Router' not found in /home/dynamiccode/public_html/myproject/vendor/cakephp/cakephp/config/bootstrap.php:22 Stack trace: #0 /home/dynamiccode/public_html/myproject/config/bootstrap.php(30): require() #1 /home/dynamiccode/public_html/myproject/webroot/myfile.php(13): require('/home/dynamiccode/...') #2 {main} thrown in /home/dynamiccode/public_html/myproject/vendor/cakephp/cakephp/config/bootstrap.php on line 22

    ReplyDelete

Post a Comment

Popular posts from this blog

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your...

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

Solution-windows 'expo' is not recognized as an internal or external command

Solution for expo is not recognized as an internal or external command,operable program or batch file in Windows 10 Sometimes expo will not work globally mostly in windows 10, If you are facing same issue then follow the below Steps 1) Click on windows button and search for  " Environment variables"  and click on "Edit the system environment variables" 2) Now you will see a popup like below screen. Then you need to click on Environment Variables. (Please see highlight part in below image)     3)Then click on new button that i have highlighted in below image 4. Then a popup will open and you need to fill details like below mentioned Variable Name :Path Variable Value: %USERPROFILE%\AppData\Roaming\npm Here we are creating a new path variable and passing location of npm.   Now Click on OK and close all the terminal windows and open new CMD or terminal and type Expo . Great now you can access expo from any...