简体   繁体   中英

Lock Service and Script Properties in Google Apps Script

I am writing a code on Google Apps Script. I need to give an unique number for each user.

At first, I wrote some code with tryLock and ScriptProperties class. It gave the same number for several persons when 6 users called the function at almost the same time. So, now I am using waitLock and ScriptProperties.

Is there any difference between tryLock and waitLock in terms of locking ability? Also, I am wondering the update timing of ScriptProperties. Is it updated immediately for all users?

If you give advises on this issue, I really appreciate it.


//My code with tryLock: This gave the same number for 3 users in a test by 6 users.

var glock = LockService.getPublicLock();
if( glock.tryLock(10000) )
{
  var val = ScriptProperties.getProperty(proName) * 1 + 1;
  ScriptProperties.setProperty(proName, val);
  glock.releaseLock();
  return val;
} else { return null; }

//Another code with waitLock: This gave an unique number for each in a test by 8 users.

var val = null;
try{
  var glock = LockService.getPublicLock();
  glock.waitLock(10000);
  val = ScriptProperties.getProperty(proName) * 1 + 1;
  ScriptProperties.setProperty(proName, val);
  glock.releaseLock();
} catch (e) { }
return val;

If you don't need the IDs to be sequential you might be better off using the timestamp instead:

var glock = LockService.getPublicLock();
if (glock.tryLock(10000)) {
  var val = (new Date()).getTime();
  glock.releaseLock();
  return val;
} else { 
  return null; 
}

The methods tryLock() and waitLock() work the same, it's just that the first returns false if it can't obtain a lock while the second throws an exception in that case.

If you want to identify unique users of a script, you can use a property in the userproperties store, since each user has a unique store. If you've never seen him before then generate a unique number using a time stamp or something in his user property store. If you have seen him before his store will already contain the unique number you generated on his last visit. If you need to consolidate all numbers, copy them to the script property store.

For example, see http://ramblings.mcpher.com/Home/excelquirks/gassnips/anonymoususerregistration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM