registerTimer method

Future<void> registerTimer({
  1. required String workflowExecutionId,
  2. required String stepName,
  3. required Duration duration,
})

Registers a durable timer for a workflow sleep.

Persists the timer to the store, marks the execution as SUSPENDED, and returns a Future that completes when the timer fires.

Implementation

Future<void> registerTimer({
  required String workflowExecutionId,
  required String stepName,
  required Duration duration,
}) async {
  final now = DateTime.now().toUtc();
  final fireAt = now.add(duration);
  final timerId = 'timer-$workflowExecutionId-$stepName';

  final timer = WorkflowTimer(
    workflowTimerId: timerId,
    workflowExecutionId: workflowExecutionId,
    stepName: stepName,
    fireAt: fireAt.toIso8601String(),
    status: TimerStatus.pending,
    createdAt: now.toIso8601String(),
  );
  await _store.saveTimer(timer);

  final execution = await _store.loadExecution(workflowExecutionId);
  if (execution != null) {
    await _store.saveExecution(
      execution.copyWith(
        status: const Suspended(),
        updatedAt: utcNow(),
      ),
    );
  }

  final completer = Completer<void>();
  _completers[timerId] = completer;

  _scheduleOrFire(timerId, fireAt);

  return completer.future;
}