Reputation: 147
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?
Upvotes: 0
Views: 321
Reputation: 2807
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.sleep
inside an actor may indeed block the flow).
You can use reactWithin
:
import java.util.Date
import math.max
def some_method = {
var last_transmission_time = 0
loop {
val current_time = (new Date).getTime
reactWithin(max(0, last_transmission_time + 100 - current_time)) {
// actor reaction cases
case TIMEOUT => {
// Transmit something
last_transmission_time = (new Date).getTime
}
}
}
}
The last_transmission_time
saves 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.
Upvotes: 1