Skip to content

Instantly share code, notes, and snippets.

@GDmac
Created September 10, 2012 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GDmac/3694530 to your computer and use it in GitHub Desktop.
Save GDmac/3694530 to your computer and use it in GitHub Desktop.
Codigniter and MySQL GET_LOCK
<?php
/*
- codeigniter, by default, uses persistent database connections, this is problematic in that the
lock is never automatically released on connection termination (what else is to expect with persistent
connections). However after a script ends you also never can RELEASE_LOCK() anymore, at least it didn't
work overhere while testing. The script really has to make sure to release the lock before ending
(shutdown_function) if it uses persistent DB connections.
- Due to a bug in mysql < 5.5.3 any script that tries to get a lock that already is in use, will wait
until timeout has expired, and still report 0 (cannot get lock). The script should use IS_FREE_LOCK()
and/or IS_USED_LOCK() before trying to get a lock.
*/
// what is the lock status
$sql = 'SELECT IS_FREE_LOCK("ci_cron_lock") as lockstatus';
$query = $this->db->query($sql);
$row = $query->row();
if ($row->lockstatus == 0)
{
// lock not free, wait and try again? exit?
}
else
{
// try to get a lock for 60 seconds
$sql = 'SELECT GET_LOCK("ci_cron_lock", 60) as lockstatus';
$query = $this->db->query($sql);
$row = $query->row();
if ($row->lockstatus == 0)
{
// could not get a lock, exit
}
else
{
/*
* cron tasks go here
*
*/
$sql = 'SELECT RELEASE_LOCK("ci_cron_lock") as lockstatus';
$query = $this->db->query($sql);
$row = $query->row();
if ($row->lockstatus == 0)
{
// could not release lock
}
else
{
// lock released
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment