How to Set Up Cron Job in CakePHP Project

Tips for Setting Up Cron Job in CakePHP Project

Cron is a feature that allows you to run specific functions at a certain time automatically. All we need to do is create the function and then set the cron to call that function. Then, it will call the function automatically in our selected time. 

 

Here, I will be discussing the setting up of the cron into CakePHP project. So let me start. I will not show CakePHP setup and email configuration in my system, as this is not our main focus. 

 

Now I will create a function to send emails to all users. 

So assuming that we have a table named as `users` where all users data and their emails are available. Next, create this functionality in your UsersController.php

 

    public function sendEmailToUsers()

    {

        $allUsers = $this->Users->find('all');

        foreach($allUsers as $key => $user)

        {              

  $usersEmail[] = $user['email'];            

        }

        If ($usersEmail) {

         $email = new Email();

        $email->from('[email protected]')

            ->to($usersEmail)

            ->emailFormat('html')

            ->setsubject("Cron setup tutorial from Fokrule Hasan")

            ->send("Hi, this is a cron email setup tutorial from Forkule Hasan. Organization is SJ Innovation");

}

}

In above function this line will fetch all users from the users table : $allUsers = $this->Users->find('all');

Then the foreach loop will save all the users’ emails into an array named as $usersEmail. 

After that, we are calling the script for sending the email. Now run this function by entering the URL into the browser (yourprojecturl/users/sendEmailToUsers) and you will see that the email is getting sent to the users’ emails, if you have done everything correctly. 

 

However, there is something more that we need to do. We can call the URL from the browser and hitting that URL will send the email to the user. We need to stop this as this is the cron functionality, so it should run only from the cron call. To do this, we will first add a variable in our bootstrap.php file like this:

 

Configure::write(cronValidationToken, ’somerandomstringandnumber ’);

 

Now we will update our email sending functionality like this:

 

public function sendEmailToUsers($cronToken = null)

    {

If ( $cronToken == Configure::read(‘cronValidationToken’)) { 

        $allUsers = $this->Users->find('all');

        foreach($allUsers as $key => $user)

        {

                $usersEmail[] = $user['email'];

            

        }

If ($usersEmail) {

         $email = new Email();

        $email->from('[email protected]')

            ->to($usersEmail)

            ->emailFormat('html')

            ->setsubject("Cron setup tutorial from Fokrule Hasan")

            ->send("Hi, this is a cron email setup tutorial from Forkule Hasan. Organization is SJ Innovation");

}

    }

}

 

Now if you run this function as you run above (yourprojecturl/users/sendEmailToUsers) will not send any email. That means it is validated now. 

 

Our email sending functionality is complete. Now let’s set up the cron functionality. 

For cron functionality, first create a folder named as `crons` into your project root directory. Inside this crons folder, add a php file named as send_cron_email_to_users.php (You can name it whatever you want with the php extension).

Now paste the code below into the send_cron_email_to_users.php file

 

<?php

namespace App\Controller;

require dirname(__DIR__) . '/vendor/autoload.php';

use App\Controller\AppController;

use App\Controller\UsersController; 

use Cake\Core\Configure;

if (!defined('DS')) { 

    define('DS', DIRECTORY_SEPARATOR);

  require_once(dirname(dirname(__FILE__)).DS.'config'.DS.'bootstrap.php');

  require_once(dirname(dirname(__FILE__)).DS.'src'.DS.'Controller'.DS.'AppController.php');

 

  $UsersController = new UsersController();

  

  $securityHash = Configure::read('cronValidationToken'); // send a security hash so that will only be sent from cron

  $UsersController->sendEmailToUsers($securityHash);

 

Here, you will see that I am sending a security hash that we had added into bootstrap.php file and by this hash code, we are validating our email sending functionality. That is for setting up the cron from the CakePHP side. 

 

Now we will be setting up the cron from the server side so that our email will be sent at a specific time. To do this, first deploy your code into a server. Now login into your cpanel and search for cron jobs. You should get something like this. (Interface might vary from server to server)


How to Set Up Cron Job in CakePHP Project

Click on this cron job and it will redirect to the cron setup page. Here, you will get a page like this. 

How to Set Up Cron Job in CakePHP Project

From the image above, you can see in point 1 & 2, that they are showing how we can call our cron function which we need to put in point 4. So copy the first example portion upto /public_html/. Then, add your function name next to this. So it will be like this: `/usr/local/bin/php /home/project/public_html/crons/send_cron_email_to_users.php`

Now put this into point 4 (command section). Now set the date and time from point 3 and save. We are done with the cron setup from the server as well. 

 

Caution / tips 

> Never forget to add validation on the cron function. Otherwise, if anyone calls the function manually it will run.

> Try checking empty variables before any action to prevent unexpected errors if there is no data into the variable.

 

Fokrul Hasan
Fokrul Hasan
Happiness in helping others

Happiness in helping others

Anuj Azrenkar
Learn how to Build Productivity Application With ReactJs

How To Build A Simple Productivity Application With ReactJs

Makdia Hussain
Tips for Building a Positive Environment

Significance of positive work environment

Rishabh Talauliker