| 41 | * @since 4.0.0 |
| 42 | */ |
| 43 | export const make = <E, R>(options: { |
| 44 | readonly name: string |
| 45 | readonly cron: Cron.Cron |
| 46 | readonly execute: Effect.Effect<void, E, R> |
| 47 | |
| 48 | /** |
| 49 | * Choose a shard group to run this cron job on. |
| 50 | */ |
| 51 | readonly shardGroup?: string | undefined |
| 52 | |
| 53 | /** |
| 54 | * Controls whether the next cron job is based on the time of the previous |
| 55 | * run. |
| 56 | * |
| 57 | * **Details** |
| 58 | * |
| 59 | * Defaults to `false`, meaning the next run will be calculated from the |
| 60 | * current time. |
| 61 | */ |
| 62 | readonly calculateNextRunFromPrevious?: boolean | undefined |
| 63 | |
| 64 | /** |
| 65 | * If set, the cron job will skip execution if the scheduled time is older |
| 66 | * than this duration. |
| 67 | * |
| 68 | * **When to use** |
| 69 | * |
| 70 | * Use to prevent running jobs that were scheduled too far in the past. |
| 71 | * |
| 72 | * **Details** |
| 73 | * |
| 74 | * Defaults to "1 day". |
| 75 | */ |
| 76 | readonly skipIfOlderThan?: Duration.Input | undefined |
| 77 | }): Layer.Layer<never, never, Sharding | Exclude<R, Scope>> => { |
| 78 | const CronEntity = Entity.make(`ClusterCron/${options.name}`, [ |
| 79 | Rpc.make("run", { |
| 80 | payload: CronPayload |
| 81 | }) |
| 82 | .annotate(Persisted, true) |
| 83 | .annotate(Uninterruptible, true) |
| 84 | ]) |
| 85 | .annotate(ClusterSchema.ShardGroup, () => options.shardGroup ?? "default") |
| 86 | .annotate(ClusterSchema.ClientTracingEnabled, false) |
| 87 | |
| 88 | const InitialRun = Singleton.make( |
| 89 | `ClusterCron/${options.name}`, |
| 90 | Effect.gen(function*() { |
| 91 | const now = yield* DateTime.now |
| 92 | const next = DateTime.fromDateUnsafe(Cron.next(options.cron, now)) |
| 93 | const entityId = options.calculateNextRunFromPrevious ? "initial" : DateTime.formatIso(next) |
| 94 | const client = (yield* CronEntity.client)(entityId) |
| 95 | yield* client.run({ dateTime: next }, { discard: true }) |
| 96 | }), |
| 97 | { shardGroup: options.shardGroup } |
| 98 | ) |
| 99 | |
| 100 | const skipIfOlderThan = Option.fromUndefinedOr(options.skipIfOlderThan).pipe( |