Last active
June 11, 2020 10:17
-
-
Save cm-kazup0n/6807bad84f2f99f530fd46ef0eece824 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.{Executors, TimeUnit} | |
import cats.effect._ | |
import cats.implicits._ | |
import com.typesafe.scalalogging.StrictLogging | |
import scala.concurrent.ExecutionContext | |
import scala.concurrent.duration._ | |
@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements")) | |
object AsyncExample extends App with StrictLogging { | |
val nProcess = 5 | |
//実行すると「waitだけ待ってタスクを起動しそのFiberを返す」IO | |
def invokeLater[A](wait: FiniteDuration, n: String)(io: IO[A])(implicit cs: ContextShift[IO], | |
timer: Timer[IO]): IO[Fiber[IO, A]] = | |
for { | |
_ <- info(s"[process $n] wait for $wait") | |
_ <- timer.sleep(wait) | |
fiber <- io.start | |
} yield fiber | |
def info(msg: => String): IO[Unit] = IO(logger.info(msg)) | |
def withThreadPool(size: Int, timeout: FiniteDuration): Resource[IO, ExecutionContext] = | |
Resource | |
.make(IO(Executors.newFixedThreadPool(size)))(es => | |
IO { | |
es.shutdown() | |
es.awaitTermination(timeout.toMillis, TimeUnit.MILLISECONDS) | |
() | |
}).map(ExecutionContext.fromExecutorService) | |
withThreadPool(nProcess, 60.seconds) | |
.use { ec => | |
IO { | |
implicit val cs: ContextShift[IO] = IO.contextShift(ec) | |
implicit val timer: Timer[IO] = IO.timer(ec) | |
val fibers = | |
Range(0, nProcess) | |
.map(n => | |
invokeLater(500.millis, n.toString) { | |
for { | |
_ <- info(s"[process $n] **** main task started") | |
_ <- timer.sleep(5.seconds) //時間がかかる処理 | |
_ <- info(s"[process $n] **** main task done ****") | |
} yield () | |
}).toList.sequence.unsafeRunSync() | |
fibers.map(_.join).sequence.unsafeRunSync() | |
() | |
} | |
}.unsafeRunSync() | |
} |
Author
cm-kazup0n
commented
Jun 11, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment