简体   繁体   中英

AKKA timeout on message

I'm using java with akka. I have this situation:

Actor A sends a message to actor B.

B waits a timeout and, if in this timeout no identical message(same type of message) occours, sends a message to actor C.

How can I implement it? What I have to write in B onReceive method?

public void onReceive(Object message){
        if(message instanceof EventOccurred){
             //wait a timeout to see if other EventOccurred message are   coming               
             //and then send a messago to actor C
        }
} 

In my project I have a file system watcher who receives events when a file is modified,created or deleted (This is actor A), on first I'm watching only a file.

When an event on this file occours my actor A sends a message to another actor(actor B) that first wait a timeout and secondly,if no other events occurred on that file(so if no other message are arrived on actor B), sends a message to actor C that calculate an hash of that file.

@Snickers3192 I implemented all this things I wanted only to know if it's really possible with akka.

Maybe ReceiveTimeout can help you. It's a message driven non-blocking way to receive a timeout. From Akka docs:

setReceiveTimeout defines the inactivity timeout after which the sending of a ReceiveTimeout message is triggered

public class MyReceiveTimeoutUntypedActor extends UntypedActor {

    public MyReceiveTimeoutUntypedActor() {
        // To set an initial delay
        getContext().setReceiveTimeout(Duration.create("30 seconds"));
    }

    public void onReceive(Object message) {
        if (message.equals("Hello")) {
            // To set in a response to a message
            getContext().setReceiveTimeout(Duration.create("1 second"));
        } else if (message instanceof ReceiveTimeout) {
            // To turn it off
            getContext().setReceiveTimeout(Duration.Undefined());
        } else {
           unhandled(message);
        }
    }
}

See also:

if you want to wait for any message, you simply set a receiveTimeout - Viktor Klang https://stackoverflow.com/a/12754034/1956540

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