Laravel Cron to keep executing manually even for a long time

Author - Komal Dhiman

Laravel Cron to keep executing manually even for a long time

The cron jobs we create in Laravel can be very time consuming if they have much to do. They may take a few minutes to execute completely. While testing the cron by executing it manually, we usually face the issue of ‘Broken Pipe’ and get this below error in our console –
packet_write_wait: Connection to IP port 22: Broken pipe

This error occurs when our server (to which we are connected through SSH) is idle for a few minutes (according to your server’s maximum idle time settings). When the server does not receive any command then the connection automatically gets disconnected and we get this error on the console. When the connection with the server gets disconnected our cron stops executing.

To prevent this we can keep the server busy until our cron job executes completely. To do this, we can keep outputting some text to the Console while our cron executes so that the server remains busy in the output of the text and the connection remains stable.

Code to write:

$this->line(“/****Write any statement here*****/”);

We write this statement in the handle() function of the command where the action is to be performed.

Example:

public function handle()
{
	$users = User::all();
	foreach($users as $user){
		$this->line("Keep Server busy…….”);
//Command code
}
}

In this example, we are fetching all the users and performing some action on each user. Let us assume that there are so many users that performing an action on each user is taking longer than usual. By writing $this->line(“Keep Server busy…….”); in the code, we are keeping the server busy in writing “Keep Server busy…….” to the Console. It is preventing the server from being disconnected.

In this way, our server will be busy in outputting the text and our cron will execute completely.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *