| 24 | * @category Constructors |
| 25 | */ |
| 26 | export const make = <E, R>(options: { |
| 27 | readonly name: string |
| 28 | readonly cron: Cron.Cron |
| 29 | readonly execute: Effect.Effect<void, E, R> |
| 30 | |
| 31 | /** |
| 32 | * Choose a shard group to run this cron job on. |
| 33 | */ |
| 34 | readonly shardGroup?: string | undefined |
| 35 | |
| 36 | /** |
| 37 | * Whether to run the next cron job based from the time of the previous run. |
| 38 | * |
| 39 | * Defaults to `false`, meaning the next run will be calculated from the |
| 40 | * current time. |
| 41 | */ |
| 42 | readonly calculateNextRunFromPrevious?: boolean | undefined |
| 43 | |
| 44 | /** |
| 45 | * If set, the cron job will skip execution if the scheduled time is older |
| 46 | * than this duration. |
| 47 | * |
| 48 | * This is useful to prevent running jobs that were scheduled too far in the |
| 49 | * past. |
| 50 | * |
| 51 | * Defaults to "1 day". |
| 52 | */ |
| 53 | readonly skipIfOlderThan?: Duration.DurationInput | undefined |
| 54 | }): Layer.Layer<never, never, Sharding | Exclude<R, Scope>> => { |
| 55 | const CronEntity = Entity.make(`ClusterCron/${options.name}`, [ |
| 56 | Rpc.make("run", { |
| 57 | payload: CronPayload |
| 58 | }) |
| 59 | .annotate(Persisted, true) |
| 60 | .annotate(Uninterruptible, true) |
| 61 | ]) |
| 62 | .annotate(ClusterSchema.ShardGroup, () => options.shardGroup ?? "default") |
| 63 | .annotate(ClusterSchema.ClientTracingEnabled, false) |
| 64 | |
| 65 | const InitialRun = Singleton.make( |
| 66 | `ClusterCron/${options.name}`, |
| 67 | Effect.gen(function*() { |
| 68 | const now = yield* DateTime.now |
| 69 | const next = DateTime.unsafeFromDate(Cron.next(options.cron, now)) |
| 70 | const client = (yield* CronEntity.client)(DateTime.formatIso(next)) |
| 71 | yield* client.run({ dateTime: next }, { discard: true }) |
| 72 | }), |
| 73 | { shardGroup: options.shardGroup } |
| 74 | ) |
| 75 | |
| 76 | const skipIfOlderThan = Option.fromNullable(options.skipIfOlderThan).pipe( |
| 77 | Option.map(Duration.decode), |
| 78 | Option.getOrElse(() => Duration.days(1)) |
| 79 | ) |
| 80 | |
| 81 | const effect = Effect.fnUntraced(function*(dateTime: DateTime.Utc) { |
| 82 | const now = yield* DateTime.now |
| 83 | if (DateTime.lessThan(dateTime, DateTime.subtractDuration(now, skipIfOlderThan))) { |