When a user requests a record to edit I firstly run an UPDATE query that locks the record.
$query = “UPDATE table SET locked_on = $date_time, locked_by = Suser_id WHERE id = $id AND (locked_by = 0 OR locked_by = $user_id OR locked_on < $time_out)”;
where:
$date_time = time(); ie is the current time measured in the number of seconds since the Unix Epoch (I tend to control all my date and times by reference to the PHP server)
$time_out is $date_time adjusted by the required lock out period
eg for a six minute lock $time_out = $date_time – (6 * 60);
$user_id is the individual id for the user requesting the record
$id = the id of the record to be edited
If the affected rows == 1 then you can run a SELECT query and carry on with the editing process.
If the affected rows == 0 then the record is locked out to another user and, maybe you will allow read only access with a suitable message.
You need to check that the lock is still valid when you come to submit the form. For example, if the user submits the form after the time out period another user may have successfully opened it for editing. So I revalidate the lock and run the same UPDATE query before I process the form. If affected rows == 1 all is OK, and this will occur even if I try to submit the form way past the time out period provided another user has not reset the lock. If affected rows == 0, then I need to create a message that the user has been timed out.
When the form is finally processed unlock the record by adding the following to the query that updates the record:
“... $locked_by = 0 ...”
Now I can build on this process by adding some JavaScript that fires off an http request before the lock out period. The request runs the same UPDATE query thus constantly refreshing the lock for so long as the user has his browser open. Hence the request must parse the $user_id and $id values. The JavaScript could have a long stop period at which point it stops refreshing but kicks in a countdown timer. For example, let’s say I set a 6 minute lock out period. I might refresh the lock using the http request once every 2 minutes up to a maximum of 9 refreshes (20 minutes in all) and then a 3 minute countdown kicks in. The 3 minute countdown would also kick in if the http request failed; so we need to make sure that the sum of the interval and countdown (2 + 3 = 5mins) is less than the desired time out period.
This approach allows a short(ish) lock out period (6 mins in my example) but provided the browser remains open and active that period can be extended to a maximum (23 mins in my example).
There is no need to run a CRON or any other scheduled script to release the locks since they are timestamped and this controls the ability to subsequently lock the record to a new user.