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

     1  package scheduler_test
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/asynkron/protoactor-go/actor"
     9  	"github.com/asynkron/protoactor-go/scheduler"
    10  )
    11  
    12  var system = actor.NewActorSystem()
    13  
    14  // Use the timer scheduler to repeatedly send messages to an actor.
    15  func ExampleTimerScheduler_sendRepeatedly() {
    16  	var wg sync.WaitGroup
    17  
    18  	wg.Add(2)
    19  
    20  	count := 0
    21  	props := actor.PropsFromFunc(func(c actor.Context) {
    22  		if v, ok := c.Message().(string); ok {
    23  			count++
    24  			fmt.Println(count, v)
    25  			wg.Done()
    26  		}
    27  	})
    28  
    29  	pid := system.Root.Spawn(props)
    30  
    31  	s := scheduler.NewTimerScheduler(system.Root)
    32  	cancel := s.SendRepeatedly(1*time.Millisecond, 1*time.Millisecond, pid, "Hello")
    33  
    34  	wg.Wait()
    35  	cancel()
    36  
    37  	// Output:
    38  	// 1 Hello
    39  	// 2 Hello
    40  }