github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/23_proto_actor/receivetimeout/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	console "github.com/AsynkronIT/goconsole"
     9  	"github.com/AsynkronIT/protoactor-go/actor"
    10  )
    11  
    12  type NoInfluence string
    13  
    14  func (NoInfluence) NotInfluenceReceiveTimeout() {}
    15  
    16  func main() {
    17  	log.Println("Receive timeout test")
    18  
    19  	c := 0
    20  
    21  	rootContext := actor.EmptyRootContext
    22  	props := actor.PropsFromFunc(func(context actor.Context) {
    23  		switch msg := context.Message().(type) {
    24  		case *actor.Started:
    25  			context.SetReceiveTimeout(1 * time.Second)
    26  
    27  		case *actor.ReceiveTimeout:
    28  			c++
    29  			log.Printf("ReceiveTimeout: %d", c)
    30  
    31  		case string:
    32  			log.Printf("received '%s'", msg)
    33  			if msg == "cancel" {
    34  				fmt.Println("Cancelling")
    35  				context.SetReceiveTimeout(0)
    36  			}
    37  
    38  		case NoInfluence:
    39  			log.Println("received a no-influence message")
    40  
    41  		}
    42  	})
    43  
    44  	pid := rootContext.Spawn(props)
    45  	for i := 0; i < 6; i++ {
    46  		rootContext.Send(pid, "hello")
    47  		time.Sleep(102 * time.Millisecond)
    48  	}
    49  
    50  	log.Println("hit [return] to send no-influence messages")
    51  	console.ReadLine()
    52  
    53  	for i := 0; i < 6; i++ {
    54  		rootContext.Send(pid, NoInfluence("hello"))
    55  		time.Sleep(500 * time.Millisecond)
    56  	}
    57  
    58  	log.Println("hit [return] to send a message to cancel the timeout")
    59  	console.ReadLine()
    60  	rootContext.Send(pid, "cancel")
    61  
    62  	log.Println("hit [return] to finish")
    63  	console.ReadLine()
    64  
    65  	rootContext.Stop(pid)
    66  }