Skip to content

Commit

Permalink
Update WorkCleaningJob.scala
Browse files Browse the repository at this point in the history
Improving the code for more reability
  • Loading branch information
IcyNation authored Jan 10, 2025
1 parent 1eb77a1 commit 7202240
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions app/src/main/scala/WorkCleaningJob.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package lila.fishnet

import cats.effect.IO
import cats.effect.kernel.Resource
import cats.effect.{IO, Resource, Deferred}
import cats.syntax.all.*
import org.typelevel.log4cats.Logger

Expand All @@ -11,9 +10,30 @@ trait WorkCleaningJob:
def run(): Resource[IO, Unit]

object WorkCleaningJob:
def apply(executor: Executor)(using Logger[IO]): WorkCleaningJob = new:
def apply(executor: Executor, cleanInterval: FiniteDuration = 3.seconds, initialDelay: FiniteDuration = 5.seconds)(using Logger[IO]): WorkCleaningJob = new:
def run(): Resource[IO, Unit] =
(Logger[IO].info("Start cleaning job") *>
IO.sleep(5.seconds) *>
(IO.realTimeInstant.flatMap(now => executor.clean(now.minusSeconds(3))) *>
IO.sleep(3.seconds)).foreverM).background.void
for
_ <- Resource.make(Logger[IO].info("Starting cleaning job").attempt.void) { _ =>
Logger[IO].info("Cleaning job has been stopped").attempt.void
}
stopSignal <- Resource.make(Deferred[IO, Unit]) { _ =>
Logger[IO].info("Stopping cleaning job").attempt.void
}
_ <- Resource.eval(runCleaningJob(stopSignal, cleanInterval, initialDelay))
yield ()

private def runCleaningJob(stopSignal: Deferred[IO, Unit], cleanInterval: FiniteDuration, initialDelay: FiniteDuration)(using Logger[IO]): IO[Unit] =
(for
_ <- IO.sleep(initialDelay)
_ <- Logger[IO].info("Cleaning job started")
_ <- (IO.realTimeInstant.flatMap(now => executor.clean(now.minusSeconds(cleanInterval.toSeconds))) *>
IO.sleep(cleanInterval)).foreverM
).guaranteeCase {
case ExitCase.Completed => Logger[IO].info("Cleaning job completed successfully")
case ExitCase.Error(e) => Logger[IO].error(e)("Cleaning job encountered an error")
case ExitCase.Canceled => Logger[IO].info("Cleaning job was canceled")
}.start.flatMap { fiber =>
stopSignal.get.flatMap(_ => fiber.cancel).handleErrorWith { e =>
Logger[IO].error(e)("Error while stopping the cleaning job")
}
}

0 comments on commit 7202240

Please sign in to comment.