Effect CommunityEC
Effect Community2mo ago
43 replies
Kam

Best Practices for Providing Services in Scheduled Tasks

Curious what's the best way to run something every once in a while, according to a provided schedule (a cron schedule, for example).
More precisely, I'm curious about what's the proper way to provide the service. In my head, it would make sense to provide it inside the part that is repeated at a schedule, rather than providing it outside the schedule. But maybe I'm misunderstanding how those things fit together?

Here is a simplified example of the situation, with EnvLive as the services to provide (a MySql client, in particular), a schedule to repeat every 2 days, and myFn, the effectful function I want to see executed every 2 days.

Is this the correct way (providing inside the repeat logic)?

const EnvLive = Layer.merge(DatabaseLayer, Logger.pretty);

const schedule = Schedule.fixed('2 days');

const myFn = ...   // effectful function

pipe(
  myFn(),
  Effect.provide(EnvLive),
  Effect.repeat(schedule),
  Effect.runFork,
);


Or is that the preferred way (providing the service outside the repeat):

const EnvLive = Layer.merge(DatabaseLayer, Logger.pretty);

const schedule = Schedule.fixed('2 days');

const myFn = ...   // effectful function

pipe(
  myFn(),
  Effect.repeat(schedule),
  Effect.provide(EnvLive),
  Effect.runFork,
);


I'm asking because in my mind, each time we do the provide, it borrows a connection from the database pool, and then release it automatically, and it would make sense to do so each time the schedule runs, rather than never releasing it.

Is my understanding wrong?
Was this page helpful?