Programatically updating node immediately after creation causes PDOException I'm working on a Drupal 7 site where nodes represent jobs in a queue. When a node is created, a custom module with hook_node_insert launches another program using exec. This program tells Drupal that the job has finished by requesting a page on the site at site.com/jobcomplete/NODE_ID/IS_ERROR. The callback for this page then does:

$node = node_load((int)$node_id);
$node-&gt;field_completed[LANGUAGE_NONE][0]['value'] = ($error == 1) ? -1 : time();
node_save($node);


The problem with this is that sometimes the program errors out almost as soon as it's started. When this happens the callback is called before the request that created the node in the first place is completely finished, resulting in 'PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded' when node_save is called.

How can I get the callback to wait for the request that created the node to finish before trying to update it? sleep() doesn't seem to work.

Thanks.
Drupal provides a Lock API for this purpose - to handle when multiple processes are competing for a resource.

In your case, you need to acquire a lock and release it when finished, checking if that lock is available prior to processing from the other component.

i.e:


lock_acquire
lock_release
lock_wait


Although not directly related, you may also be interested in the Queue API for other queue based processing tasks.