Run a Background Job for the Lifetime of the Application
Many services need work that runs on its own while the application serves requests: refreshing a cache, sending a heartbeat, flushing a buffer. In this guide we start a periodic job when the application starts and have it stop cleanly when the application shuts down. The recipe has three parts: repeat the job with a Schedule, start it with ZIO#forkScoped, and do both inside a ZLayer.scoped, so that the job lives exactly as long as the layer.
The Problemโ
A first attempt is often a loop that sleeps and calls itself, started on a fiber (a lightweight thread) that nobody owns:
import zio._
def refreshCache: UIO[Unit] = ZIO.unit
// Runs forever, and nothing can stop it.
def loop: UIO[Nothing] = refreshCache *> ZIO.sleep(5.minutes) *> loop
val startJob: UIO[Fiber.Runtime[Nothing, Nothing]] = loop.forkDaemon
forkDaemon attaches the fiber to the global scope, so it keeps running until the process exits. At shutdown, the resources the job uses, such as a database connection pool, are released while the job may still be using them. The job also never reports that it has stopped, and a test that builds the application twice ends up with two jobs.
The rest of this guide replaces the loop with a Schedule, and the forkDaemon with a start that is tied to the lifetime of a layer.
Prerequisitesโ
Add ZIO to your build:
// ZIO core: ZLayer.scoped, forkScoped, repeat and Schedule
libraryDependencies += "dev.zio" %% "zio" % "2.1.27"
We assume you know what a fiber and a ZLayer are. If you want a refresher on schedules, read Schedule Step by Step. Every program below uses short intervals so that a run takes under a second.
The Recipeโ
We build a PriceCache service. Other code reads prices from it, and a background job keeps the prices fresh. The service is a layer, and the job starts when the layer is built:
val live: ZLayer[Any, Nothing, PriceCache] =
ZLayer.scoped {
for {
// ... create the Refs that hold the version and the prices ...
_ <- refresh
_ <- refresh
.schedule(Schedule.spaced(100.millis))
.forkScoped
} yield PriceCacheLive(prices)
}
(The complete file is below. This sketch leaves out the helper values, and the two Console.printLine calls that print the shutdown messages in the output.)
There are four things to notice:
ZLayer.scopedbuilds a layer from an effect that needs aScope. The scope closes when the layer is released, which for a layer you pass toprovidehappens when the effect ends.ZIO#forkScopedstarts the job on a new fiber and registers that fiber in the layer's scope. When the scope closes, ZIO interrupts the fiber.refresh.schedule(Schedule.spaced(100.millis))waits 100 milliseconds, runsrefresh, waits again, and so on, until the fiber is interrupted.Schedule.spacedcounts the wait from the end of the previous run, so a slow run never overlaps the next one.- The
refreshbefore the job fills the cache once, before the layer is ready. A reader of the cache never sees it empty, and if the first load fails, the layer fails to build instead of serving nothing.
ZIO#repeat and ZIO#schedule both run an effect many times. repeat runs the effect once and then waits according to the schedule. schedule waits first. Use repeat when the first run should happen right away, and schedule when the first run should wait for the first interval, as it does here after the explicit first refresh.
The program below defines the service and the layer, reads the cache four times while the job runs, and then ends the application:
RefresherExample.scala
package backgroundjob
import zio._
/**
* A price cache that a background job keeps fresh. The job starts when the
* layer is built and stops when the layer's scope closes.
*/
trait PriceCache {
def price(item: String): UIO[Option[Double]]
}
final case class PriceCacheLive(prices: Ref[Map[String, Double]]) extends PriceCache {
def price(item: String): UIO[Option[Double]] = prices.get.map(_.get(item))
}
object PriceCache {
/** Stands in for a call to a remote service. */
private def fetchPrices(version: Int): UIO[Map[String, Double]] =
ZIO.succeed(Map("apple" -> (1.0 + version / 10.0), "pear" -> (2.0 + version / 10.0)))
val live: ZLayer[Any, Nothing, PriceCache] =
ZLayer.scoped {
for {
version <- Ref.make(0)
prices <- Ref.make(Map.empty[String, Double])
refresh = for {
v <- version.updateAndGet(_ + 1)
map <- fetchPrices(v)
_ <- prices.set(map)
_ <- Console.printLine(s"job: refreshed prices (version $v)").orDie
} yield ()
// Fill the cache once before the layer is ready, then keep it fresh.
_ <- refresh
_ <- refresh
.schedule(Schedule.spaced(100.millis))
.onInterrupt(Console.printLine("job: interrupted").orDie)
.forkScoped
_ <- ZIO.addFinalizer(Console.printLine("layer: scope closed").orDie)
} yield PriceCacheLive(prices)
}
}
object RefresherExample extends ZIOAppDefault {
val readPrices: ZIO[PriceCache, Nothing, Unit] =
for {
cache <- ZIO.service[PriceCache]
_ <- ZIO.foreachDiscard(1 to 4) { _ =>
cache.price("apple").flatMap(p => Console.printLine(s"app: apple costs $p").orDie) *>
ZIO.sleep(150.millis)
}
} yield ()
val run =
readPrices.provide(PriceCache.live) *> Console.printLine("app: finished")
}
Output:
job: refreshed prices (version 1)
app: apple costs Some(1.1)
job: refreshed prices (version 2)
app: apple costs Some(1.2)
job: refreshed prices (version 3)
app: apple costs Some(1.3)
job: refreshed prices (version 4)
job: refreshed prices (version 5)
app: apple costs Some(1.5)
job: refreshed prices (version 6)
layer: scope closed
job: interrupted
app: finished
The price the application reads goes from 1.1 to 1.5 because the job kept replacing it. When the application finished, the layer's scope closed. The finalizer ran (layer: scope closed), and the job was interrupted (job: interrupted) before the program ended. The timing of the job: lines can shift by a line between runs.
In a real application that extends ZIOAppDefault, you provide the layer to your whole program (program.provide(PriceCache.live, ...)). The scope then closes when run ends, whether it ends because the work finished, a signal such as Ctrl+C interrupted it, or an error occurred.
Why forkScoped and Not fork or forkDaemonโ
ZIO has three ways to start a fiber that are easy to confuse here. They differ in what ends the fiber:
| Method | The fiber ends when | In a layer |
|---|---|---|
fork | The fiber that started it ends | Tied to the fiber that built the layer, not to the layer |
forkDaemon | The process exits | Nothing stops it when the layer is released |
forkScoped | The enclosing Scope closes, or the process exits | Stops when the layer is released |
The next program builds the same layer three times, once for each method. It closes the layer's scope, waits, and checks whether the job kept counting:
ForkKindsExample.scala
package backgroundjob
import zio._
/**
* Builds the same layer three times, once for each way of starting the job,
* closes the layer's scope, and checks whether the job is still running.
*/
object ForkKindsExample extends ZIOAppDefault {
/** A job that counts how many times it has run. */
def job(ticks: Ref[Int]): UIO[Long] =
ticks.update(_ + 1).repeat(Schedule.spaced(10.millis))
def layerWith(
ticks: Ref[Int],
start: UIO[Long] => ZIO[Scope, Nothing, Any]
): ZLayer[Any, Nothing, Unit] =
ZLayer.scoped(start(job(ticks)).unit)
def check(name: String)(start: UIO[Long] => ZIO[Scope, Nothing, Any]): UIO[Unit] =
for {
ticks <- Ref.make(0)
scope <- Scope.make
_ <- layerWith(ticks, start).build.provideEnvironment(ZEnvironment(scope))
_ <- ZIO.sleep(100.millis)
_ <- scope.close(Exit.unit)
before <- ticks.get
_ <- ZIO.sleep(100.millis)
after <- ticks.get
status = if (after > before) "still running after the scope closed" else "stopped when the scope closed"
_ <- Console.printLine(f"$name%-12s $status").orDie
} yield ()
val run =
check("fork")(_.fork) *>
check("forkDaemon")(_.forkDaemon) *>
check("forkScoped")(_.forkScoped)
}
Output:
fork still running after the scope closed
forkDaemon still running after the scope closed
forkScoped stopped when the scope closed
Only forkScoped stops the job at the right moment. With fork, the job belongs to the fiber that built the layer. In this program that fiber is still alive, so the job runs on after its layer is gone. In a real application the job would use resources that the layer has already released.
See Fiber for the full lifetime rules, and Scope for how scopes close.
What Happens When a Run Failsโ
If one run of the job fails, repeat and schedule stop, and the fiber ends with that failure. Nothing reports it. ZIO does log the failure, but at the Debug level, and the default loggers leave that level out. The cache then stops updating, and the application keeps serving old data.
The program below uses a refresh that fails on its third run. It starts the job three ways and looks at it after 200 milliseconds:
FailureExample.scala
package backgroundjob
import zio._
/**
* Shows what a failing run does to a background job, and two ways to keep the
* job alive.
*/
object FailureExample extends ZIOAppDefault {
/** A refresh that fails on its third run. */
def refresh(runs: Ref[Int]): IO[String, Unit] =
for {
n <- runs.updateAndGet(_ + 1)
_ <- ZIO.fail(s"run $n failed").when(n == 3)
_ <- Console.printLine(s" run $n ok").orDie
} yield ()
val every = Schedule.spaced(20.millis)
def demo(title: String)(job: Ref[Int] => ZIO[Any, Any, Any]): UIO[Unit] =
for {
_ <- Console.printLine(title).orDie
runs <- Ref.make(0)
fiber <- job(runs).forkDaemon
_ <- ZIO.sleep(200.millis)
done <- fiber.poll
n <- runs.get
_ <- Console.printLine(s" after 200 ms: $n runs, job ${if (done.isEmpty) "alive" else "ended"}").orDie
_ <- fiber.interrupt
} yield ()
val run =
demo("No handling:")(runs => refresh(runs).repeat(every)) *>
demo("Log the failure and carry on:")(runs =>
refresh(runs)
.catchAll(e => Console.printLine(s" refresh failed ($e), will try again").orDie)
.repeat(every)
) *>
demo("Retry the failed run:")(runs =>
refresh(runs)
.retry(Schedule.spaced(20.millis))
.repeat(every)
)
}
Output:
No handling:
run 1 ok
run 2 ok
after 200 ms: 3 runs, job ended
Log the failure and carry on:
run 1 ok
run 2 ok
refresh failed (run 3 failed), will try again
run 4 ok
run 5 ok
run 6 ok
run 7 ok
run 8 ok
run 9 ok
run 10 ok
after 200 ms: 10 runs, job alive
Retry the failed run:
run 1 ok
run 2 ok
run 4 ok
run 5 ok
run 6 ok
run 7 ok
run 8 ok
run 9 ok
run 10 ok
after 200 ms: 10 runs, job alive
Without handling, the job ended after the failed run 3. The two other versions kept going:
- Handle the failure inside each run. Put
ZIO#catchAll(orZIO#catchAllCause, if defects should not stop the job either) on the effect you repeat. Log the problem and return, and the schedule starts the next run on time. This is the best choice for a refresh job, because the next run is a fresh attempt anyway. - Retry the failed run.
ZIO#retrywith aScheduleruns the effect again after a failure. Use a schedule with a growing delay, such asSchedule.exponential, when the failure is likely to last a while, such as an unreachable service. In the output above the failed run 3 was tried again, so the next line is run 4.
In both versions the job is still a child of the layer's scope, so it stops at shutdown as before.
To see unhandled failures of background fibers while you develop, raise their log level with the Runtime.setUnhandledErrorLogLevel layer:
import zio._
object MyApp extends ZIOAppDefault {
override val bootstrap: ZLayer[Any, Any, Any] =
Runtime.setUnhandledErrorLogLevel(LogLevel.Warning)
def run = ZIO.unit
}
A fiber that ends only because it was interrupted logs nothing, so a clean shutdown stays quiet.
Letting a Run Finish Before Shutdownโ
Interruption can arrive in the middle of a run. For a cache refresh that is harmless. For a job that must not stop halfway, such as one that writes a file or sends a batch, mark the run uninterruptible. ZIO then waits for the current run to end before it stops the fiber, and the schedule never starts another one:
import zio._
def flushBuffer: UIO[Unit] = ZIO.unit
val job: ZIO[Scope, Nothing, Fiber.Runtime[Nothing, Long]] =
flushBuffer.uninterruptible
.schedule(Schedule.spaced(1.second))
.forkScoped
The wait for a long run delays shutdown by that long, so keep each run short. See Interruption for how uninterruptible regions work.
Running the Examplesโ
The companion source files for this guide live in the zio-examples/background-job directory of the ZIO repository. Clone the repository and run any program with sbt:
git clone https://github.com/zio/zio.git
cd zio/zio-examples/background-job
sbt "runMain backgroundjob.RefresherExample"
The other programs are ForkKindsExample and FailureExample. All of them live in the backgroundjob package.
Going Furtherโ
- Fiber explains the fork variants, including
forkInfor a scope you manage yourself. - Scope covers how scopes are created and closed.
- Schedule Step by Step shows the other schedules, including
fixed,exponentialand how to combine them. - Build a Concurrent Job Processor stops background workers at shutdown with
ZIO.addFinalizerandforkScopedin a larger program.