Is there a way in Scala to execute something in a loop without blocking the entire flow?
I have the following code to transmit something in Actor model
All actors send something to other actors:
def some_method
loop {
// Transmit something
Thread.sleep(100)
}
I also have some code to receive what other actors send. But the flow is not coming out of the loop. It sleeps and continues without coming out of the loop. Thus, all actors keep sending but nobody receives. How can I fix this?
If I understand you correctly, you want the transmission to occur every 100ms, but you don’t want to create another Thread for that (and a
Thread.sleepinside an actor may indeed block the flow).You can use
reactWithin:The
last_transmission_timesaves the last time a transmission was done.The reaction timeout is calculated so that a TIMEOUT will occur when the current time is the last-transmission-time + 100ms.
If a timeout occured it means over 100ms passed since the last transmission, so another transmission should be called.
If the reaction cases themselves may take a lot of time, then I don’t see any simple solution but creating another thread.
I didn’t try the code because I’m not sure that I fully understand your problem.