Skip to content

Commit

Permalink
Optimize UpdateFolderCounters Job #4374 from mahavirn/optimize-update…
Browse files Browse the repository at this point in the history
…-folder-count-job

Optimize UpdateFolderCounters Job
  • Loading branch information
freescout-help authored Nov 28, 2024
2 parents b3dbad9 + ecc9ea9 commit 8024c72
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
4 changes: 3 additions & 1 deletion app/Folder.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,9 @@ public function isIndirect()
public function updateCounters()
{
if (config('app.update_folder_counters_in_background')) {
\App\Jobs\UpdateFolderCounters::dispatch($this);
if(!\Illuminate\Support\Facades\Cache::has("folder_update_lock_{$this->id}")) {
\App\Jobs\UpdateFolderCounters::dispatch($this);
}
} else {
$this->updateCountersNow();
}
Expand Down
38 changes: 21 additions & 17 deletions app/Jobs/UpdateFolderCounters.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

namespace App\Jobs;

use App\Conversation;
use App\ConversationFolder;
use App\Folder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
Expand All @@ -15,28 +14,33 @@ class UpdateFolderCounters implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

/**
* @var Folder
*/
private $folder;

/**
* Create a new job instance.
*
* @return void
*/
// Cache lock key
private $lockKey;

public function __construct(Folder $folder)
{
$this->folder = $folder;
$this->lockKey = "folder_update_lock_{$folder->id}";
}

/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->folder->updateCountersNow();
// Check if another job is processing this folder
if (Cache::has($this->lockKey)) {
return; // Exit if already processing
}

// Set lock with a timeout of 5 minutes (adjust as needed)
Cache::put($this->lockKey, true, now()->addMinutes(5));

try {
// Perform the folder update logic
$this->folder->updateCountersNow();
} finally {
// Release the lock after processing
Cache::forget($this->lockKey);
}
}
}
}

0 comments on commit 8024c72

Please sign in to comment.