github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/context_example_setReceiveTimeout_test.go (about)

     1  package actor_test
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/asynkron/protoactor-go/actor"
     9  )
    10  
    11  type setReceiveTimeoutActor struct {
    12  	*sync.WaitGroup
    13  }
    14  
    15  // Receive is the default message handler when an actor is started
    16  func (f *setReceiveTimeoutActor) Receive(context actor.Context) {
    17  	switch context.Message().(type) {
    18  	case *actor.Started:
    19  		// when the actor starts, set the receive timeout to 10 milliseconds.
    20  		//
    21  		// the system will send an *actor.ReceiveTimeout message every time the timeout
    22  		// expires until SetReceiveTimeout is called again with a duration < 1 ms]
    23  		context.SetReceiveTimeout(10 * time.Millisecond)
    24  	case *actor.ReceiveTimeout:
    25  		fmt.Println("timed out")
    26  		f.Done()
    27  	}
    28  }
    29  
    30  // SetReceiveTimeout allows an actor to be notified repeatedly if it does not receive any messages
    31  // for a specified duration
    32  func ExampleContext_setReceiveTimeout() {
    33  	wg := &sync.WaitGroup{}
    34  	wg.Add(1)
    35  
    36  	pid := system.Root.Spawn(actor.PropsFromProducer(func() actor.Actor { return &setReceiveTimeoutActor{wg} }))
    37  	defer func() {
    38  		_ = system.Root.StopFuture(pid).Wait()
    39  	}()
    40  
    41  	wg.Wait() // wait for the ReceiveTimeout message
    42  
    43  	// Output: timed out
    44  }