github.com/aergoio/aergo@v1.3.1/p2p/p2putil/timedcall.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package p2putil
     7  
     8  import (
     9  	"fmt"
    10  	"time"
    11  )
    12  
    13  // Callable
    14  type Callable interface {
    15  	// DoCall run function. it should put result anything if call is over. It also stop  function if Cancel was called as soon as possible
    16  	DoCall(done chan<- interface{})
    17  	// Cancel should return instantly
    18  	Cancel()
    19  }
    20  
    21  // InvokeWithTimer call DoCall method of m and return if m is finished or return error if timer fires.
    22  func InvokeWithTimer(m Callable, timer *time.Timer) (interface{}, error) {
    23  	done := make(chan interface{}, 1)
    24  	go m.DoCall(done)
    25  	select {
    26  	case hsResult := <-done:
    27  		return hsResult, nil
    28  	case <-timer.C:
    29  		m.Cancel()
    30  		return nil, fmt.Errorf("timeout")
    31  	}
    32  }