Jake Vanderwerf
2026-05-11 ac444cba221832c012c0435fdc8339fe9f37febb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace JVBase\managers\queue;
use wpdb;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class Locker
{
    private string $lockKey;
    private int $timeout;
    protected wpdb $wpdb;
    private ?string $token = null;
 
    public function __construct(string $key = 'queue', int $timeout = 0)
    {
        $this->lockKey = BASE . $key . '_lock';
        $this->timeout = $timeout;
        global $wpdb;
        $this->wpdb = $wpdb;
    }
 
    /**
     * Execute callback with lock, auto-release after
     */
    public function withLock(callable $callback): void
    {
        $acquired = $this->wpdb->get_var(
            $this->wpdb->prepare(
                'SELECT GET_LOCK(%s, %d)',
                $this->lockKey,
                $this->timeout
            )
        );
 
        if ((int) $acquired !== 1) {
            // Lock already held — just exit quietly
            return;
        }
 
        try {
            $callback();
        } finally {
            $this->unlock();
        }
    }
 
    public function unlock():void
    {
        $this->wpdb->get_var(
            $this->wpdb->prepare(
                'SELECT RELEASE_LOCK(%s)',
                $this->lockKey
            )
        );
    }
}