diff --git a/docs/services/scheduler.md b/docs/services/scheduler.md
index 09e72b1260..1a4ef035ed 100644
--- a/docs/services/scheduler.md
+++ b/docs/services/scheduler.md
@@ -45,9 +45,11 @@ window are skipped. The dispatcher ticks every
Rate schedules use the same dispatcher whether created or updated directly or
through Step Functions. A changed future `StartDate` takes effect before the
-first dispatch. The dispatcher keeps its last-fire state in memory; past dates,
-restart, post-dispatch updates and re-enable timing have not been verified
-against live AWS. Fixed-anchor recurrence is not implemented.
+first dispatch. When a schedule last fired is stored with it, so with persistence
+on a restart neither fires a one-time schedule again nor fires an immediate
+catch-up for a rate or cron schedule; a one-time schedule updated to a later time
+fires again at that time. Past dates, post-dispatch updates and re-enable timing
+have not been verified against live AWS. Fixed-anchor recurrence is not implemented.
Supported target types: SQS, Lambda, SNS, ECS `RunTask`, EventBridge
`PutEvents`, and unqualified Step Functions state machine ARNs. Templated
diff --git a/src/main/java/io/floci/aws/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/floci/aws/services/scheduler/ScheduleDispatcher.java
index 91a6b2e6c9..00f1f051fc 100644
--- a/src/main/java/io/floci/aws/services/scheduler/ScheduleDispatcher.java
+++ b/src/main/java/io/floci/aws/services/scheduler/ScheduleDispatcher.java
@@ -36,8 +36,9 @@ import java.util.concurrent.TimeUnit;
*
* A single background thread ticks on a fixed interval, scans all persisted
* schedules, and invokes the target of any schedule whose next fire time has
- * passed. Per-schedule "last fire" state is kept in memory (by schedule ARN);
- * restarts reset it, matching the emulator's loose durability expectations.
+ * passed. When a schedule last fired is stored with the schedule
+ * ({@link Schedule#getLastFiredAt}), so with persistence on a restart neither fires a one-time
+ * schedule again nor fires an immediate catch-up for a rate or cron schedule.
*
* Scope of the initial implementation:
*
@@ -76,8 +77,6 @@ public class ScheduleDispatcher implements Resettable {
private final long tickIntervalSeconds;
private final boolean enabled;
private final ScheduledExecutorService executor;
- private final ConcurrentHashMap lastFireByArn = new ConcurrentHashMap<>();
- private final ConcurrentHashMap firedOnceByArn = new ConcurrentHashMap<>();
private final ConcurrentHashMap pendingRetries = new ConcurrentHashMap<>();
@Inject
@@ -115,8 +114,6 @@ public class ScheduleDispatcher implements Resettable {
}
public void clear() {
- lastFireByArn.clear();
- firedOnceByArn.clear();
pendingRetries.clear();
}
@@ -216,18 +213,16 @@ public class ScheduleDispatcher implements Resettable {
private Instant computeNextFire(Schedule schedule, Kind kind, Instant now) {
String expr = schedule.getScheduleExpression();
String tz = schedule.getScheduleExpressionTimezone();
- String arn = schedule.getArn();
+ Instant lastFire = schedule.getLastFiredAt();
return switch (kind) {
case AT -> {
- if (firedOnceByArn.containsKey(arn)) {
- yield null;
- }
- yield SchedulerExpressionParser.parseAt(expr, tz);
+ // Fired once its time came, unless it has fired since: an update to a later time re-arms it.
+ Instant at = SchedulerExpressionParser.parseAt(expr, tz);
+ yield lastFire != null && !lastFire.isBefore(at) ? null : at;
}
case RATE -> {
long intervalMs = SchedulerExpressionParser.parseRateMillis(expr);
- Instant lastFire = lastFireByArn.get(arn);
if (lastFire != null) {
yield lastFire.plusMillis(intervalMs);
}
@@ -235,9 +230,8 @@ public class ScheduleDispatcher implements Resettable {
: schedule.getCreationDate() != null ? schedule.getCreationDate() : now;
}
case CRON -> {
- Instant base = lastFireByArn.getOrDefault(arn, schedule.getCreationDate() != null
- ? schedule.getCreationDate()
- : now.minusSeconds(1));
+ Instant base = lastFire != null ? lastFire
+ : schedule.getCreationDate() != null ? schedule.getCreationDate() : now.minusSeconds(1);
yield SchedulerExpressionParser.nextCronFire(expr, base, tz);
}
};
@@ -280,8 +274,6 @@ public class ScheduleDispatcher implements Resettable {
try {
schedulerService.deleteScheduleForAccount(
schedule.getAccountId(), schedule.getName(), schedule.getGroupName(), regionOf(schedule));
- lastFireByArn.remove(schedule.getArn());
- firedOnceByArn.remove(schedule.getArn());
} catch (Exception e) {
LOG.warnv("Post-completion delete failed for {0}: {1}", schedule.getArn(), e.getMessage());
}
@@ -363,8 +355,8 @@ public class ScheduleDispatcher implements Resettable {
}
private void recordFire(Schedule schedule, Instant now) {
- lastFireByArn.put(schedule.getArn(), now);
- firedOnceByArn.put(schedule.getArn(), Boolean.TRUE);
+ schedule.setLastFiredAt(now);
+ schedulerService.recordFire(schedule, regionOf(schedule), now);
}
private static boolean isDeleteAfterCompletion(Schedule schedule) {
diff --git a/src/main/java/io/floci/aws/services/scheduler/SchedulerService.java b/src/main/java/io/floci/aws/services/scheduler/SchedulerService.java
index 29113830a8..ce542e3843 100644
--- a/src/main/java/io/floci/aws/services/scheduler/SchedulerService.java
+++ b/src/main/java/io/floci/aws/services/scheduler/SchedulerService.java
@@ -28,6 +28,7 @@ import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
@@ -178,7 +179,8 @@ public class SchedulerService implements StoredResourceArns {
"ScheduleGroup not found: " + effectiveName, 404));
}
- public void deleteScheduleGroup(String name, String region) {
+ /** Synchronized with {@link #recordFire}, so a fire recorded during the cascade cannot restore a schedule. */
+ public synchronized void deleteScheduleGroup(String name, String region) {
validateName(name);
if (DEFAULT_GROUP.equals(name)) {
throw new AwsException("ValidationException",
@@ -304,7 +306,7 @@ public class SchedulerService implements StoredResourceArns {
"Schedule not found: " + name, 404));
}
- public Schedule updateSchedule(ScheduleRequest req, String region) {
+ public synchronized Schedule updateSchedule(ScheduleRequest req, String region) {
validateName(req.getName());
validateScheduleRequest(req);
String effectiveGroup = resolveAndValidateGroup(req.getGroupName());
@@ -331,13 +333,14 @@ public class SchedulerService implements StoredResourceArns {
updated.setKmsKeyArn(req.getKmsKeyArn());
updated.setCreationDate(existing.getCreationDate());
updated.setLastModificationDate(now);
+ updated.setLastFiredAt(existing.getLastFiredAt());
scheduleStore.put(key, updated);
LOG.infov("Updated schedule: {0} in group {1}", req.getName(), effectiveGroup);
return updated;
}
- public void deleteSchedule(String name, String groupName, String region) {
+ public synchronized void deleteSchedule(String name, String groupName, String region) {
validateName(name);
String effectiveGroup = resolveAndValidateGroup(groupName);
String key = scheduleKey(region, effectiveGroup, name);
@@ -360,7 +363,24 @@ public class SchedulerService implements StoredResourceArns {
return scheduleStore.scan(k -> k.startsWith("schedule:"));
}
- public void deleteScheduleForAccount(String accountId, String name, String groupName, String region) {
+ /**
+ * Records in the stored schedule that the dispatcher fired it at {@code firedAt}. Synchronized
+ * with update and delete, so it never writes back a stale copy over an update, and a schedule
+ * deleted meanwhile, or deleted and created again under the same name, is left as it is.
+ */
+ public synchronized void recordFire(Schedule schedule, String region, Instant firedAt) {
+ String key = scheduleKey(region, schedule.getGroupName(), schedule.getName());
+ AccountAwareStorageBackend.getInAccount(scheduleStore, schedule.getAccountId(), key)
+ .filter(stored -> Objects.equals(stored.getArn(), schedule.getArn())
+ && Objects.equals(stored.getCreationDate(), schedule.getCreationDate()))
+ .ifPresent(stored -> {
+ stored.setLastFiredAt(firedAt);
+ AccountAwareStorageBackend.putInAccount(scheduleStore, schedule.getAccountId(), key, stored);
+ });
+ }
+
+ public synchronized void deleteScheduleForAccount(String accountId, String name, String groupName,
+ String region) {
String effectiveGroup = resolveAndValidateGroup(groupName);
String key = scheduleKey(region, effectiveGroup, name);
if (scheduleStore instanceof AccountAwareStorageBackend aware) {
diff --git a/src/main/java/io/floci/aws/services/scheduler/model/Schedule.java b/src/main/java/io/floci/aws/services/scheduler/model/Schedule.java
index 6402b3f383..6eabe8ba60 100644
--- a/src/main/java/io/floci/aws/services/scheduler/model/Schedule.java
+++ b/src/main/java/io/floci/aws/services/scheduler/model/Schedule.java
@@ -23,6 +23,12 @@ public class Schedule {
private String kmsKeyArn;
private Instant creationDate;
private Instant lastModificationDate;
+ /**
+ * When the dispatcher last fired the schedule, Floci's own record and never part of an API
+ * response. Stored with the schedule so a restart neither fires a one-time schedule again nor
+ * catches a recurring one up.
+ */
+ private Instant lastFiredAt;
public Schedule() {}
@@ -73,4 +79,7 @@ public class Schedule {
public Instant getLastModificationDate() { return lastModificationDate; }
public void setLastModificationDate(Instant lastModificationDate) { this.lastModificationDate = lastModificationDate; }
+
+ public Instant getLastFiredAt() { return lastFiredAt; }
+ public void setLastFiredAt(Instant lastFiredAt) { this.lastFiredAt = lastFiredAt; }
}
diff --git a/src/test/java/io/floci/aws/services/scheduler/ScheduleDispatcherTest.java b/src/test/java/io/floci/aws/services/scheduler/ScheduleDispatcherTest.java
index 4f1b8437fc..075329d101 100644
--- a/src/test/java/io/floci/aws/services/scheduler/ScheduleDispatcherTest.java
+++ b/src/test/java/io/floci/aws/services/scheduler/ScheduleDispatcherTest.java
@@ -135,6 +135,70 @@ class ScheduleDispatcherTest {
verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt());
}
+ // Catches: a restart firing a one-time schedule again, because whether it had fired lived only
+ // in the dispatcher's memory. A new dispatcher stands in for the restarted process.
+ @Test
+ void anAtScheduleStoredAsFiredDoesNotFireAgainAfterARestart() {
+ Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
+ s.setLastFiredAt(Instant.parse("2026-04-21T09:18:00Z"));
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+
+ dispatcher.tick(Instant.parse("2026-04-21T10:00:00Z"));
+
+ verify(invoker, never()).invoke(any(), any(), any(), anyInt());
+ }
+
+ @Test
+ void anAtScheduleUpdatedToALaterTimeFiresAgainAtThatTime() {
+ Schedule s = newSchedule("at1", "at(2026-04-21T11:00:00)", "ENABLED");
+ s.setLastFiredAt(Instant.parse("2026-04-21T09:18:00Z"));
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+
+ dispatcher.tick(Instant.parse("2026-04-21T10:59:50Z"));
+ verify(invoker, never()).invoke(any(), any(), any(), anyInt());
+ dispatcher.tick(Instant.parse("2026-04-21T11:00:00Z"));
+
+ verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T11:00:00Z")), any(), anyInt());
+ }
+
+ // Catches: every rate schedule firing an immediate catch-up after a restart, since its next fire
+ // fell back to its creation date when the last fire was forgotten.
+ @Test
+ void aRateScheduleResumesOneIntervalAfterItsStoredLastFire() {
+ Schedule s = newSchedule("r1", "rate(1 hour)", "ENABLED");
+ s.setLastFiredAt(Instant.parse("2026-04-21T12:00:00Z"));
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+
+ dispatcher.tick(Instant.parse("2026-04-21T12:30:00Z"));
+ verify(invoker, never()).invoke(any(), any(), any(), anyInt());
+ dispatcher.tick(Instant.parse("2026-04-21T13:00:00Z"));
+
+ verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T13:00:00Z")), any(), anyInt());
+ }
+
+ @Test
+ void aCronScheduleResumesAtTheNextOccurrenceAfterItsStoredLastFire() {
+ Schedule s = newSchedule("c1", "cron(0 * * * ? *)", "ENABLED");
+ s.setLastFiredAt(Instant.parse("2026-04-21T12:00:05Z"));
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+
+ dispatcher.tick(Instant.parse("2026-04-21T12:30:00Z"));
+ verify(invoker, never()).invoke(any(), any(), any(), anyInt());
+ dispatcher.tick(Instant.parse("2026-04-21T13:00:00Z"));
+
+ verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T13:00:00Z")), any(), anyInt());
+ }
+
+ @Test
+ void aFireIsRecordedInTheStoredSchedule() {
+ Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
+ when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
+
+ dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"));
+
+ verify(schedulerService).recordFire(eq(s), any(), eq(Instant.parse("2026-04-21T09:18:00Z")));
+ }
+
@Test
void deletesAtScheduleWhenActionAfterCompletionIsDelete() {
Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
diff --git a/src/test/java/io/floci/aws/services/scheduler/SchedulerServiceTest.java b/src/test/java/io/floci/aws/services/scheduler/SchedulerServiceTest.java
index 6b68ebdd61..040e7e3a65 100644
--- a/src/test/java/io/floci/aws/services/scheduler/SchedulerServiceTest.java
+++ b/src/test/java/io/floci/aws/services/scheduler/SchedulerServiceTest.java
@@ -1,10 +1,12 @@
package io.floci.aws.services.scheduler;
+import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
+import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.services.scheduler.model.DeadLetterConfig;
import io.floci.aws.services.scheduler.model.FlexibleTimeWindow;
import io.floci.aws.services.scheduler.model.RetryPolicy;
@@ -14,10 +16,14 @@ import io.floci.aws.services.scheduler.model.ScheduleRequest;
import io.floci.aws.services.scheduler.model.Target;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@@ -48,6 +54,107 @@ class SchedulerServiceTest {
}
+ private Schedule createRateSchedule(SchedulerService schedulers, String name) {
+ return schedulers.createSchedule(newRequest(name, null, "rate(1 hour)", new FlexibleTimeWindow("OFF", null),
+ new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
+ }
+
+ @Test
+ void aRecordedFireIsKeptByAnUpdate() {
+ Schedule created = createRateSchedule(service, "fired");
+ Instant firedAt = Instant.parse("2026-04-21T12:00:00Z");
+
+ service.recordFire(created, REGION, firedAt);
+ service.updateSchedule(newRequest("fired", null, "rate(2 hours)", new FlexibleTimeWindow("OFF", null),
+ new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
+
+ assertEquals(firedAt, service.getSchedule("fired", null, REGION).getLastFiredAt());
+ }
+
+ // Catches: the dispatcher's record of a fire bringing back a schedule deleted while it fired, or
+ // marking a new schedule created under the same name as already fired.
+ @Test
+ void aFireIsNotRecordedOnADeletedOrRecreatedSchedule() {
+ Schedule created = createRateSchedule(service, "gone");
+ service.deleteSchedule("gone", null, REGION);
+
+ service.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z"));
+ assertThrows(AwsException.class, () -> service.getSchedule("gone", null, REGION));
+
+ Schedule recreated = createRateSchedule(service, "gone");
+ created.setCreationDate(recreated.getCreationDate().minusSeconds(60));
+ service.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z"));
+ assertNull(service.getSchedule("gone", null, REGION).getLastFiredAt());
+ }
+
+ // Catches: a fire recorded while a group delete cascades through its schedules writing one back,
+ // so it lived on in a deleted group and kept firing. The delete holds the lock until it is done.
+ @Test
+ void aFireIsNotRecordedWhileItsGroupIsBeingDeleted() throws Exception {
+ CountDownLatch deleting = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ InMemoryStorage schedules = new InMemoryStorage<>() {
+ @Override
+ public void delete(String key) {
+ deleting.countDown();
+ try {
+ release.await(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ super.delete(key);
+ }
+ };
+ SchedulerService schedulers = new SchedulerService(new InMemoryStorage<>(), schedules,
+ new RegionResolver(REGION, "000000000000"));
+ schedulers.createScheduleGroup("team", Map.of(), REGION);
+ Schedule created = schedulers.createSchedule(newRequest("in-group", "team", "rate(1 hour)",
+ new FlexibleTimeWindow("OFF", null),
+ new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
+
+ Thread groupDelete = Thread.ofPlatform().start(() -> schedulers.deleteScheduleGroup("team", REGION));
+ assertTrue(deleting.await(5, TimeUnit.SECONDS), "the cascade should reach the schedule");
+ Thread fire = Thread.ofPlatform().start(
+ () -> schedulers.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z")));
+ // Without the lock the fire runs to completion here instead of parking on the service's monitor.
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (fire.getState() != Thread.State.BLOCKED && fire.isAlive() && System.nanoTime() < deadline) {
+ Thread.sleep(5);
+ }
+ assertEquals(Thread.State.BLOCKED, fire.getState(), "recording a fire should wait for the delete");
+ release.countDown();
+ groupDelete.join();
+ fire.join();
+
+ assertTrue(schedules.scan(key -> true).isEmpty(), "the deleted group's schedule must stay deleted");
+ }
+
+ // Catches BL-385 across a real restart: the last fire written to disk is there when the stores are
+ // read back, so the dispatcher neither re-fires a one-time schedule nor catches a recurring one up.
+ @Test
+ void aRecordedFireSurvivesAReloadFromDisk(@TempDir Path dir) {
+ Path groups = dir.resolve("scheduler-groups.json");
+ Path schedules = dir.resolve("scheduler-schedules.json");
+ SchedulerService before = new SchedulerService(
+ new PersistentStorage<>(groups, new TypeReference