Example #1
0
File: raft.go Project: divtxt/raft
// Start the ConsensusModule running with the given ChangeListener.
//
// This starts a goroutine that drives ticks.
//
// Should only be called once.
func (cm *ConsensusModule) Start(changeListener ChangeListener) error {
	cm.mutex.Lock()
	defer cm.mutex.Unlock()

	if changeListener == nil {
		return errors.New("'changeListener' cannot be nil")
	}

	if cm.ticker != nil {
		return ErrAlreadyStartedOnce
	}

	cm.passiveConsensusModule.SetChangeListener(changeListener)

	cm.stopped = false

	// Start the ticker goroutine
	cm.ticker = util.NewTicker(cm.safeTick, cm.tickerDuration)

	return nil
}
Example #2
0
func TestTicker(t *testing.T) {
	var n int32 = 0

	getN := func() int32 {
		return atomic.LoadInt32(&n)
	}

	f := func() {
		atomic.AddInt32(&n, 1)
	}

	ticker := util.NewTicker(f, 10*time.Millisecond)

	if getN() != 0 {
		t.Fatal(getN())
	}

	time.Sleep(15 * time.Millisecond)
	if getN() != 1 {
		t.Fatal(getN())
	}

	time.Sleep(10 * time.Millisecond)
	if getN() != 2 {
		t.Fatal(getN())
	}

	time.Sleep(10 * time.Millisecond)
	if getN() != 3 {
		t.Fatal(getN())
	}

	ticker.StopAsync()

	time.Sleep(10 * time.Millisecond)
	if getN() != 3 {
		t.Fatal(getN())
	}
}