1

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;
4

2 回答 2

1

如果您不需要 ID 是连续的,则最好使用时间戳:

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

方法tryLock()waitLock()工作方式相同,只是第一个在无法获得锁时返回false,而第二个在这种情况下抛出异常。

于 2012-06-06T15:21:40.443 回答
0

如果要识别脚本的唯一用户,可以使用 userproperties 存储中的属性,因为每个用户都有唯一的存储。如果您以前从未见过他,那么使用时间戳或他的用户属性存储中的某些东西生成一个唯一编号。如果您在他的商店之前见过他,那么您在他上次访问时生成的唯一编号已经包含在内。如果您需要合并所有数字,请将它们复制到脚本属性存储区。

例如,请参阅http://ramblings.mcpher.com/Home/excelquirks/gassnips/anonymoususerregistration

于 2017-03-18T18:29:15.940 回答