| 1 | /** |
| 2 | * @title Creating Layers that run background tasks |
| 3 | * |
| 4 | * Use Layer.effectDiscard to encapsulate background tasks without a service interface. |
| 5 | */ |
| 6 | import { NodeRuntime } from "@effect/platform-node" |
| 7 | import { Effect, Layer } from "effect" |
| 8 | |
| 9 | // Use Layer.effectDiscard when you want to create a layer that runs an effect |
| 10 | // but does not provide any services. |
| 11 | const BackgroundTask = Layer.effectDiscard(Effect.gen(function*() { |
| 12 | yield* Effect.logInfo("Starting background task...") |
| 13 | |
| 14 | yield* Effect.gen(function*() { |
| 15 | while (true) { |
| 16 | yield* Effect.sleep("5 seconds") |
| 17 | yield* Effect.logInfo("Background task running...") |
| 18 | } |
| 19 | }).pipe( |
| 20 | Effect.onInterrupt(() => Effect.logInfo("Background task interrupted: layer scope closed")), |
| 21 | Effect.forkScoped |
| 22 | ) |
| 23 | })) |
| 24 | |
| 25 | // Run the background task layer. It will start when the layer is launched and |
| 26 | // will be automatically interrupted when the layer scope is closed (e.g. when |
| 27 | // the program exits). |
| 28 | BackgroundTask.pipe( |
| 29 | Layer.launch, |
| 30 | NodeRuntime.runMain |
| 31 | ) |