Saturday, January 27, 2024

[SOLVED] Cron jobs with laravel using hostinger

Issue

I had problem setting up cron jobs to send automated emails under hostinger server. I tested out the automated email function through smtp under local environment using php artisan schedule:work to run the scheduled task. The email is sent out without a problem. Then i created a script in my public folder following this tutorial tutorial

The cron job config is

/bin/sh /home/u765133174/domains/eurofinsmy.net/public_html/eurotracks/public/script.sh

and the script.sh is

#!/bin/sh
cd /home/u765133174/public_html/eurotracks/public && php artisan schedule:run >> /dev/null 2>&1

What did i did wrong? My guess is there's something wrong with the script but I couldn't quite figured how. The automated email just wouldnt send out after hosting


Solution

I had same problem on hostinger. From that I have resolved with one trick inside project.

I have created get route for cron execution and created a php file on root path of project.

Ex : in web.php create one route of type get form call cron like

Route::get('/cronsStartToWorkEmailSend', function () {
    \Artisan::call('emailsending:cron');
    return true;
});

In root path of project create one file called as cronsStartToWorkEmailSend.php and add a code for curl call for cron job run.

<?php

$url = 'https://your_project_domain/cronsStartToWorkEmailSend';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);

$data = curl_exec($curl);

curl_close($curl);
  
?>

And Now you can register cron job with type php selection from hostinger to call your cronsStartToWorkEmailSend.php file

enter image description here

So basically what happens from this code structure.

  1. When php file called via daemons on server on regular interval of time cronsStartToWorkEmailSend.php will call.
  2. When cronsStartToWorkEmailSend.php call at that time our route cronsStartToWorkEmailSend will call.
  3. When route cronsStartToWorkEmailSend will call at that time with help of this command \Artisan::call('emailsending:cron') our cron will be triggered.


Answered By - NIKUNJ PATEL
Answer Checked By - Candace Johnson (WPSolving Volunteer)