如果我从SBT shell运行这个程序,然后取消它,它将继续打印"hello“。我得离开SBT让它停下来。为什么会这样呢?
import cats.effect.{ExitCode, IO, IOApp}
import fs2.Stream
import scala.concurrent.duration._
object FS2 extends IOApp {
override def run(args: List[String]) =
Stream.awakeEvery[IO](5.seconds).map { _ =>
println("hello")
}.compile.drain.as(ExitCode.Error)
}发布于 2021-03-07 00:13:48
正如注释中已经提到的,您的应用程序运行在另一个线程中,并且它永远不会终止,因为流是无限的,所以当应用程序接收到像SIGTERM或SIGINT这样的信号时,您必须手动终止它(每当您点击ctrl+c终止应用程序时,它就发出)。
你可以这样做:
interruptWhen。例如:
import sun.misc.Signal
object FS2 extends IOApp {
override def run(args: List[String]): IO[ExitCode] = for {
cancel <- Deferred[IO, Either[Throwable, Unit]] //deferred used as flat telling if terminations signal
//was received
_ <- (IO.async_[Unit]{ cb =>
Signal.handle(
new Signal("INT"), //INT and TERM signals are nearly identical, we have to handle both
(sig: Signal) => cb(Right(()))
)
Signal.handle(
new Signal("TERM"),
(sig: Signal) => cb(Right(()))
)
} *> cancel.complete(Right(()))).start //after INT or TERM signal is intercepted it will complete
//deferred and terminate fiber
//we have to run method start to run waiting for signal in another fiber
//in other case program will block here
app <- Stream.awakeEvery[IO](1.seconds).map { _ => //your stream
println("hello")
}.interruptWhen(cancel).compile.drain.as(ExitCode.Error) //interruptWhen ends stream when deferred completes
} yield app
}当您在shell中单击ctrl + c时,此版本的应用程序将终止。
https://stackoverflow.com/questions/66372308
复制相似问题