The Cron module lets you define schedules in a style similar to UNIX cron expressions.
It also supports partial constraints (e.g., certain months or weekdays), time zone awareness through the DateTime module, and robust error handling.
This module helps you:
Create a Cron instance from individual parts.
Parse and validate cron expressions.
Match existing dates to see if they satisfy a given cron schedule.
Find the next occurrence of a schedule after a given date.
Iterate over future dates that match a schedule.
Convert a Cron instance to a Schedule for use in effectful programs.
Creating a Cron
You can define a cron schedule by specifying numeric constraints for seconds, minutes, hours, days, months, and weekdays. The make function requires you to define all fields representing the schedule’s constraints.
Example (Creating a Cron)
1
import {
import Cron
Cron,
import DateTime
DateTime } from"effect"
2
3
// Build a cron that triggers at 4:00 AM
4
// on the 8th to the 14th of each month
5
const
constcron:Cron.Cron
cron=
import Cron
Cron.
constmake: (values: {
readonlyseconds?:Iterable<number> |undefined;
readonlyminutes:Iterable<number>;
readonlyhours:Iterable<number>;
readonlydays:Iterable<number>;
readonlymonths:Iterable<number>;
readonlyweekdays:Iterable<number>;
readonlytz?:DateTime.TimeZone|undefined;
}) =>Cron.Cron
Creates a Cron instance.
@param ― constraints - The cron constraints.
@since ― 2.0.0
make({
6
seconds?: Iterable<number>|undefined
seconds: [0], // Trigger at the start of a minute
7
minutes: Iterable<number>
minutes: [0], // Trigger at the start of an hour
8
hours: Iterable<number>
hours: [4], // Trigger at 4:00 AM
9
days: Iterable<number>
days: [8, 9, 10, 11, 12, 13, 14], // Specific days of the month
Attempt to create a named time zone from a IANA time zone identifier.
If the time zone is invalid, an IllegalArgumentException will be thrown.
@since ― 3.6.0
zoneUnsafeMakeNamed("Europe/Rome") // Optional time zone
13
})
seconds, minutes, and hours: Define the time of day.
days and months: Specify which calendar days and months are valid.
weekdays: Restrict the schedule to specific days of the week.
tz: Optionally define the time zone for the schedule.
If any field is left empty (e.g., months), it is treated as having “no constraints,” allowing any valid value for that part of the date.
Parsing Cron Expressions
Instead of manually constructing a Cron, you can use UNIX-like cron strings and parse them with parse or unsafeParse.
parse
The parse(cronExpression, tz?) function safely parses a cron string into a Cron instance. It returns an Either, which will contain either the parsed Cron or a parsing error.
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stderr with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *")
Checking Dates with match
The match function allows you to determine if a given Date (or any DateTime.Input) satisfies the constraints of a cron schedule.
If the date meets the schedule’s conditions, match returns true. Otherwise, it returns false.
Example (Checking if a Date Matches a Cron Schedule)
1
import {
import Cron
Cron } from"effect"
2
3
// Suppose we have a cron that triggers at 4:00 AM
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *")
6
7
const
constcheckDate:Date
checkDate=new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
Date("2025-01-08 04:00:00")
8
9
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The next function determines the next date that satisfies a given cron schedule, starting from a specified date. If no starting date is provided, the current time is used as the starting point.
If next cannot find a matching date within a predefined number of iterations, it throws an error to prevent infinite loops.
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
console.log(Cron.unsafeParse("0 4 8-14 * *"))
// Output:
// {
// _id: 'Cron',
// tz: { _id: 'Option', _tag: 'None' },
// seconds: [ 0 ],
// minutes: [ 0 ],
// hours: [ 4 ],
// days: [
// 8, 9, 10, 11,
// 12, 13, 14
// ],
// months: [],
// weekdays: []
// }
@since ― 2.0.0
unsafeParse("0 0 4 8-14 * *", "UTC")
6
7
// Specify the starting point for the search
8
const
constafter:Date
after=new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
To generate multiple future dates that match a cron schedule, you can use the sequence function. This function provides an infinite iterator of matching dates, starting from a specified date.
Example (Generating Future Dates with an Iterator)
// Get the first matching date after the start date
14
console.log(iterator.next().value)
15
// Output: 2021-01-08T04:00:00.000Z
16
17
// Get the second matching date after the start date
18
console.log(iterator.next().value)
19
// Output: 2021-01-09T04:00:00.000Z
Converting to Schedule
The Schedule module allows you to define recurring behaviors, such as retries or periodic events. The cron function bridges the Cron module with the Schedule module, enabling you to create schedules based on cron expressions or Cron instances.
cron
The Schedule.cron function generates a Schedule that triggers at the start of each interval defined by the provided cron expression or Cron instance. When triggered, the schedule produces a tuple [start, end] representing the timestamps (in milliseconds) of the cron interval window.
Example (Creating a Schedule from a Cron)
1
import {
2
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect,
3
import Schedule
Schedule,
4
import TestClock
TestClock,
5
import Fiber
Fiber,
6
import TestContext
TestContext,
7
import Cron
Cron,
8
import Console
Console
9
} from"effect"
10
11
// A helper function to log output at each interval of the schedule
function (typeparameter) Ain <A>(action:Effect.Effect<A>, schedule:Schedule.Schedule<[number, number], void>):void
A>(
13
action: Effect.Effect<A, never, never>
action:
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
interfaceEffect<outA, outE=never, outR=never>
The Effect interface defines a value that describes a workflow or job,
which can succeed or fail.
Details
The Effect interface represents a computation that can model a workflow
involving various types of operations, such as synchronous, asynchronous,
concurrent, and parallel interactions. It operates within a context of type
R, and the result can either be a success with a value of type A or a
failure with an error of type E. The Effect is designed to handle complex
interactions with external resources, offering advanced features such as
fiber-based concurrency, scheduling, interruption handling, and scalability.
This makes it suitable for tasks that require fine-grained control over
concurrency and error management.
To execute an Effect value, you need a Runtime, which provides the
environment necessary to run and manage the computation.
@since ― 2.0.0
@since ― 2.0.0
Effect<
function (typeparameter) Ain <A>(action:Effect.Effect<A>, schedule:Schedule.Schedule<[number, number], void>):void
A Schedule<Out, In, R> defines a recurring schedule, which consumes values
of type In, and which returns values of type Out.
The Schedule type is structured as follows:
┌─── The type of output produced by the schedule
│ ┌─── The type of input consumed by the schedule
│ │ ┌─── Additional requirements for the schedule
▼ ▼ ▼
Schedule<Out, In, Requirements>
A schedule operates by consuming values of type In (such as errors in the
case of Effect.retry, or values in the case of Effect.repeat) and
producing values of type Out. It determines when to halt or continue the
execution based on input values and its internal state.
The inclusion of a Requirements parameter allows the schedule to leverage
additional services or resources as needed.
Schedules are defined as a possibly infinite set of intervals spread out over
time. Each interval defines a window in which recurrence is possible.
When schedules are used to repeat or retry effects, the starting boundary of
each interval produced by a schedule is used as the moment when the effect
will be executed again.
Schedules can be composed in different ways:
Union: Combines two schedules and recurs if either schedule wants to
continue, using the shorter delay.
Intersection: Combines two schedules and recurs only if both schedules want
to continue, using the longer delay.
Sequencing: Combines two schedules by running the first one fully, then
switching to the second.
In addition, schedule inputs and outputs can be transformed, filtered (to
terminate a schedule early in response to some input or output), and so
forth.
A variety of other operators exist for transforming and combining schedules,
and the companion object for Schedule contains all common types of
schedules, both for performing retrying, as well as performing repetition.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
Effect.gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Repeats an effect based on a specified schedule or until the first failure.
Details
This function executes an effect repeatedly according to the given schedule.
Each repetition occurs after the initial execution of the effect, meaning
that the schedule determines the number of additional repetitions. For
example, using Schedule.once will result in the effect being executed twice
(once initially and once as part of the repetition).
If the effect succeeds, it is repeated according to the schedule. If it
fails, the repetition stops immediately, and the failure is returned.
The schedule can also specify delays between repetitions, making it useful
for tasks like retrying operations with backoff, periodic execution, or
performing a series of dependent actions.
You can combine schedules for more advanced repetition logic, such as adding
delays, limiting recursions, or dynamically adjusting based on the outcome of
each execution.
constintersect: <number, unknown, never>(that:Schedule.Schedule<number, unknown, never>) => <Out, In, R>(self:Schedule.Schedule<Out, In, R>) =>Schedule.Schedule<[Out, number], In, R> (+1overload)
Combines two schedules, continuing only if both schedules want to continue,
using the longer delay.
Details
This function takes two schedules and creates a new schedule that only
continues execution if both schedules allow it. The interval between
recurrences is determined by the longer delay between the two schedules.
The output of the resulting schedule is a tuple containing the outputs of
both schedules. The input type is the intersection of both schedules' input
types.
This is useful when coordinating multiple scheduling conditions where
execution should proceed only when both schedules permit it.
@see ― intersectWith If you need to use a custom merge function.
A schedule that recurs a fixed number of times before terminating.
Details
This schedule will continue executing until it has been stepped n times,
after which it will stop. The output of the schedule is the current count of
recurrences.
Returns a new schedule that runs the given effectful function for each output
before continuing execution.
Details
This function allows side effects to be performed on each output produced by
the schedule. It does not modify the schedule’s behavior but ensures that the
provided function f runs after each step.
new (value:number|string|Date) =>Date (+3 overloads)
Date(
typeOut: [number, number]
Out[0]), new
var Date:DateConstructor
new (value:number|string|Date) =>Date (+3 overloads)
Date(
typeOut: [number, number]
Out[1])]
31
)
32
)
33
)
34
),
35
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
constfork: <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>
Creates a new fiber to run an effect concurrently.
Details
This function takes an effect and forks it into a separate fiber, allowing it
to run concurrently without blocking the original effect. The new fiber
starts execution immediately after being created, and the fiber object is
returned immediately without waiting for the effect to begin. This is useful
when you want to run tasks concurrently while continuing other tasks in the
parent fiber.
The forked fiber is attached to the parent fiber's scope. This means that
when the parent fiber terminates, the child fiber will also be terminated
automatically. This feature, known as "auto supervision," ensures that no
fibers are left running unintentionally. If you prefer not to have this auto
supervision behavior, you can use
forkDaemon
or
forkIn
.
When to Use
Use this function when you need to run an effect concurrently without
blocking the current execution flow. For example, you might use it to launch
background tasks or concurrent computations. However, working with fibers can
be complex, so before using this function directly, you might want to explore
higher-level functions like
raceWith
,
zip
, or others that can
manage concurrency for you.
@see ― forkWithErrorHandler for a version that allows you to handle errors.
@example
import { Effect } from"effect"
constfib= (n:number):Effect.Effect<number> =>
n <2
? Effect.succeed(n)
: Effect.zipWith(fib(n -1), fib(n -2), (a, b) => a + b)
Accesses a TestClock instance in the context and increments the time
by the specified duration, running any actions scheduled for on or before
the new time in order.
Joins the fiber, which suspends the joining fiber until the result of the
fiber has been determined. Attempting to join a fiber that has erred will
result in a catchable error. Joining an interrupted fiber will result in an
"inner interruption" of this fiber, unlike interruption triggered by
another fiber, "inner interruption" can be caught and recovered.
constprovide: <TestServices, never, never>(layer:Layer<TestServices, never, never>) => <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<...> (+9overloads)
Provides necessary dependencies to an effect, removing its environmental
requirements.
Details
This function allows you to supply the required environment for an effect.
The environment can be provided in the form of one or more Layers, a
Context, a Runtime, or a ManagedRuntime. Once the environment is
provided, the effect can run without requiring external dependencies.
You can compose layers to create a modular and reusable way of setting up the
environment for effects. For example, layers can be used to configure
databases, logging services, or any other required dependencies.
@see ― provideService for providing a service to an effect.
construnPromise: <A, E>(effect:Effect.Effect<A, E, never>, options?: {
readonlysignal?:AbortSignal;
} |undefined) =>Promise<A>
Executes an effect and returns the result as a Promise.
Details
This function runs an effect and converts its result into a Promise. If the
effect succeeds, the Promise will resolve with the successful result. If
the effect fails, the Promise will reject with an error, which includes the
failure details of the effect.
The optional options parameter allows you to pass an AbortSignal for
cancellation, enabling more fine-grained control over asynchronous tasks.
When to Use
Use this function when you need to execute an effect and work with its result
in a promise-based system, such as when integrating with third-party
libraries that expect Promise results.
@see ― runPromiseExit for a version that returns an Exit type instead
of rejecting.
@example
// Title: Running a Successful Effect as a Promise
This function takes a cron expression as a string and attempts to parse it
into a Cron instance. If the expression is valid, the resulting Cron
instance will represent the schedule defined by the cron expression.
If the expression is invalid, the function throws a ParseError.
You can optionally provide a time zone (tz) to interpret the cron
expression in a specific time zone. If no time zone is provided, the cron
expression will use the default time zone.
@example
import { Cron } from"effect"
// At 04:00 on every day-of-month from 8 through 14.
Creates a schedule that recurs based on a cron expression.
Details
This schedule automatically executes at intervals defined by a cron
expression. It triggers at the beginning of each matched interval and
produces timestamps representing the start and end of the cron window.
The cron expression is validated lazily, meaning errors may only be
detected when the schedule is executed.
@since ― 2.0.0
cron(
constcron:Cron.Cron
cron)
48
49
// Define a dummy action to repeat
50
const
constaction:Effect.Effect<void, never, never>
action=
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
constvoid:Effect.Effect<void, never, never>
export void
Represents an effect that does nothing and produces no value.
When to Use
Use this effect when you need to represent an effect that does nothing.
This is useful in scenarios where you need to satisfy an effect-based
interface or control program flow without performing any operations. For
example, it can be used in situations where you want to return an effect
from a function but do not need to compute or return any result.