1

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 ?

WeiChing 林煒清
  • 4,452
  • 3
  • 30
  • 65
  • 1
    Sorry, but it is not clear what behavior you really want. If you use `scheduleWithFixedDelay`, it means the task is not executed immediately, so the "main program" will continue to run and can be executing arbitrary code (outside of the method that scheduled the task) when the exception happens. Where do you expect the exception to be passed to? So unless you write some custom code that will make the "main program" wait for the scheduled task, there is no way to pass the exception back because there is no such place as "back" anymore in this scenario. – SergGr Jul 14 '18 at 14:53

1 Answers1

0

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.

JVS
  • 521
  • 6
  • 18