tryAcquireSchedulerLock function
Try to acquire the scheduler lock for the current session. Returns true on success, false if another live session holds it.
Uses exclusive create for atomic test-and-set. If the file exists:
- Already ours -> true (idempotent re-acquire)
- Another live PID -> false
- Stale (PID dead / corrupt) -> unlink and retry once
Implementation
Future<bool> tryAcquireSchedulerLock({
SchedulerLockOptions? opts,
String? sessionId,
}) async {
final dir = opts?.dir;
final identity = opts?.lockIdentity ?? sessionId ?? 'unknown';
final lock = SchedulerLock(
sessionId: identity,
pid: pid,
acquiredAt: DateTime.now().millisecondsSinceEpoch,
);
if (await _tryCreateExclusive(lock, dir: dir)) {
_lastBlockedBy = null;
return true;
}
final existing = await _readLock(dir: dir);
// Already ours (idempotent).
if (existing?.sessionId == identity) {
if (existing!.pid != pid) {
await File(
_getLockPath(dir: dir),
).writeAsString(jsonEncode(lock.toJson()));
}
return true;
}
// Another live session -- blocked.
if (existing != null && _isProcessRunning(existing.pid)) {
if (_lastBlockedBy != existing.sessionId) {
_lastBlockedBy = existing.sessionId;
}
return false;
}
// Stale -- unlink and retry once.
try {
await File(_getLockPath(dir: dir)).delete();
} catch (_) {}
if (await _tryCreateExclusive(lock, dir: dir)) {
_lastBlockedBy = null;
return true;
}
// Another session won the recovery race.
return false;
}