简体   繁体   中英

In Scala Monix Scheduler how to propagate exceptions to main program?

I have a Monix Scheduler that scheduling error-prone task:

import scala.concurrent.duration._
import monix.eval.Task
import monix.execution.Scheduler
import java.time._

scheduler.scheduleWithFixedDelay(0.seconds, 1.seconds) {
    IO(println("qq"))
        .map{ _ => 
            if (Instant.now.getEpochSecond % 5 == 0) 
                throw new Exception()
        }
        .unsafeRunSync()
}

The problem is -- if the task inside scheduler throw exception, the scheduler stops and exception does not propagate to main program. I want the main program get the exception and handle it (in fact I want to stop the whole program.).

I may well just call sys.exit() inside, but I think it is not ideal because parent process should supervise the child process.

When using Task I can catch it from main program by task.runSyncUnsafe() , for Scheduler is there way to do the same thing ?

You can't catch exception because the scheduler runs asynchronously.

If you are using cats-effect IO (or monix Task), you could use .attempt, and then left map on the Either to handle exceptions. But you have to explicitly cancel the scheduled job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM