I made a game that needs to be controlled from the backend, and the function should run every second.
$abc = new CronJobController();
$abc->updateGame();
I run it by a cronjob that runs after every 2 minutes, and that is the code:
Route::get('/triggerServer', function () {
Log::error("triggering");
$endTime = CarbonCarbon::now()->addMinutes(2);
while ($endTime > CarbonCarbon::now()) {
Log::error("every time running well");
// Call the function you want to execute every second
$abc = new CronJobController();
$abc->updateGame();
sleep(1); // Sleep for 1 second
}
});
It runs well, but after some time, the cronjob changes to */21 or */16. I researched and found that it’s a server-side issue. I need to contact them for resolution. In my research, I discovered that cronjobs longer than 15 minutes might cause issues. So I changed it to run every 15 minutes. However, I don’t know why my while loop stops after 5 minutes.
I also created an artisan command, and when I run it in the shared hosting terminal, it runs well. But after closing the terminal, it stops.
protected $signature = 'send:requests';
public function __construct()
{
parent::__construct();
}
public function handle()
{
Log::error("every time running well");
while (true) {
// Call the function you want to execute every second
$abc = new CronJobController();
$abc->updateGame();
sleep(1); // Sleep for 1 second
}
}
My question is, what is the best way to run the server, or do I have to change my approach? And how can I trigger the function at the start?