Friday, April 6, 2018

How to Make Async Requests in PHP | Methods for synchronous processes in PHP | Making synchronous function call in PHP | Make sure same function will not execute parallel


<?php
function executeSync($key, $closure) {
    $sem = getSemGetCustom($key);
    if(getSemAcquireCustom($sem)) {
        $closure();

        getSemReleaseCustom($sem);
    }
    else {
        throw new \Exception("Processing");
    }
}

function getSemGetCustom($key) {
    return fopen(sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.sem', 'w+');
}

function getSemAcquireCustom($sem) {
    return flock($sem, LOCK_EX);
}

function getSemReleaseCustom($sem) {
    return flock($sem, LOCK_UN);
}

function logText($text) {
    file_put_contents('data.txt', $text.PHP_EOL , FILE_APPEND | LOCK_EX);
}

$id = $_GET["id"];
$closure = function() use($id) {
    logText("STARTING-$id");
    sleep(1);
    logText("FINISHED-$id");
};

executeSync("KEY", $closure);
Or if you want to set timeout for lock
<?php
public static function lockAndExecute($key, Closure $closure, $timeout_seconds = 5) {
    $file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($key) . '.tmp';
    $handle = fopen($file, 'w+');
    while (!flock($handle, LOCK_EX | LOCK_NB)) {
        usleep(1000 * 249);
        $timeout_seconds = $timeout_seconds - 0.25;
        if ($timeout_seconds <= 0) {
            throw new Exception("Unable to acquire lock");
        }
    }
    try {
        return $closure();
    }
    finally {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Popup</title>
    <meta name="viewport" content="user-scalable=yes, initial-scale=1, maximum-scale=1,minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.get("exec.php", { id: 1 });
            $.get("exec.php", { id: 2 });
            $.get("exec.php", { id: 3 });
            $.get("exec.php", { id: 4 });
            $.get("exec.php", { id: 5 });
            $.get("exec.php", { id: 6 });
            $.get("exec.php", { id: 7 });
            $.get("exec.php", { id: 8 });
            $.get("exec.php", { id: 9 });
            $.get("exec.php", { id: 10 });
        });
    </script>
</head>
<body>

</body>
</html>

You can see that function "executeSync" executing synchronously.

No comments:

Post a Comment