November, 05 2023

A Note On Running Horizon On CPanel Using Cron Jobs

In my quest to improve the CPanel experience for Laravel developers, I have been trying to find a better way to keep Laravel Horizon running on cPanel.

My Current Solution (That Didn't Work)

In order to keep this simple, I created a closure command which I registered inside the routes/console.php file.

Here is the PHP code snippets:

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Process;

Artisan::command('cpanel:horizon', function () {
    $horizon = Process::run('php artisan horizon:status');

    if (!$horizon->seeInOutput('running')) {
        $horizon = Process::run('php artisan horizon &');
    }

    $this->info('Horizon is running...');
});

Using Laravel's process feature, this code snippet checks and starts Horizon if it's not running.

The "&" at the end of the Horzion command — php artisan horizon & will make this process start in the background.

I then added this command to my cPanel cron job to run every 5 minutes, but it didn't work.

Why It Didn't Work

Even though my current setup works locally that was not the case on cPanel.

Why?

This is because cPanel cron jobs terminated any child process that it spwns up before it terminates the parent process.

I tried setsid command as part of the cron job command. If this works well, this command will spawn up a process that is not dependent on the parent process but that doesn't work yet or let me put it better; I am yet to figure it out.

I believe this is a cPanel feature not a bug.

You can reach out to me on X(formerly Twitter) if you have any questions.

Join my inner circle newsletter

Be the first to hear about anything I publish, launch, or think is helpful for you. Subscribe here

Hey, have you tried Litehost lately ?

Litehost is a web hosting platform for PHP & Laravel developers with Composer, Git, PHP & CLI pre-installed. Try it now