 : alarm-expired? ( alarm n -- ? )
     [ start>> ] dip <= ;
 
-: next-alarm-time ( alarm -- n )
+: set-next-alarm-time ( alarm -- alarm )
     ! start + ceiling((now - start) / interval) * interval
     nano-count 
     over start>> -
     over interval>> / ceiling
     over interval>> *
-    swap start>> + ; inline
+    over start>> + >>iteration-scheduled ; inline
 
 DEFER: call-alarm-loop
 
 : loop-alarm ( alarm -- )
     nano-count over
-    [ iteration-begin>> - ] [ interval>> ] bi < [
-        [ next-alarm-time sleep-until ] keep
-        call-alarm-loop
+    [ iteration-scheduled>> - ] [ interval>> ] bi <
+    [ set-next-alarm-time ] dip [
+        [ iteration-scheduled>> sleep-until ]
+        [ call-alarm-loop ] bi
     ] [
         0 sleep-until call-alarm-loop
     ] if ;

: <alarm> ( quot start interval -- alarm )
    alarm new
        swap >nanoseconds >>interval
        swap >nanoseconds nano-count + >>start
        swap >>quot ;

: register-alarm ( alarm -- )
    dup start>> alarms get-global heap-push* drop


PRIVATE>

: add-alarm ( quot start interval -- alarm )
    <alarm> [ register-alarm ] keep ;

