Level 122
why do you need so much complexity every second? Consider how to simplify this. Remember, to run this every second, your code must take less than a second to run, or you will end up more and more jobs running
I was using custom cronjob (with while true) to make my app work properly and I decided to change it to laravel schedule and I did it, here's the console.php:
<?php
use App\Http\Controllers\ShareTestController;
Schedule::call(function () {
$test = new ShareTestController();
$test->timeUpGroup();
})->everySecond();
Schedule::call(function () {
$test = new ShareTestController();
$test->timeUp();
})->everySecond();
and ShareTestController
public function timeUpGroup()
{
try {
$bot = new Nutgram(env("TELEGRAM_TOKEN"));
$currentTime = Carbon::now();
$endTimeThreshold = $currentTime->format('H:i:s');
$groups = GroupTest::where("is_ready", ">=", 2)
->whereNotNull("end_time")
->where("end_time", "<=", $endTimeThreshold)
->get();
if ($groups->isEmpty()) {
return response()->json(['message' => 'Testlar topilmadi']);
}
foreach ($groups as $group) {
$this->sendPollToGroup($bot, $group->question_slug, $group->group_id);
usleep(33333);
}
return response()->json(['message' => 'Testlar muvaffaqiyatli yakunlandi']);
} catch (\Exception $e) {
return response()->json(['message' => 'An error occurred: ' . $e->getMessage()], 500);
}
}
public function timeUp()
{
try {
$bot = new Nutgram(env("TELEGRAM_TOKEN"));
} catch (ContainerExceptionInterface|NotFoundExceptionInterface $e) {
Log::error("Error occurred: " . $e->getMessage());
}
$currentTime = Carbon::now();
$endTimeThreshold = $currentTime->format('H:i:s');
$res = UserTestProgress::where("test_end_time", "!=", null)
->where("is_paused", false)
->whereNotNull("shared_test_slug")
->where("test_end_time", "<=", $endTimeThreshold)
->get();
if (!$res->isEmpty()) {
foreach ($res as $r) {
$time = SharedTestController::getTestTime($r->shared_test_slug);
TestController::updateTestTime($time, $r->user_id);
TestController::checkCorrect(id: $r->user_id, answer: "notGiven");
$this->sendPoll($bot, category: $r->shared_test_slug, user_id: $r->user_id, timeUp: true);
usleep(33333); // avoid hitting sending limit
}
}
}
the problem is, when I do it with custom cronejob it was fst enought but now it's very slow and I don't know what to do.
how can I make it as fast as it was?
Please or to participate in this conversation.