golang 超时器

没找到工作 可能是今年最后一更了 😔 直接code吧.

下面是超时试用默认处理

type Timer struct {
	Arg []string
}
func (t *Timer) Run(f func(a interface{}),sec uint64)  {
	c := make(chan struct{})
	go func() {
		f(t.Arg)
		c <- struct{}{}
	}()

	select {
	// 接收到值就代表未超时
	case <- c:
		return
		//fmt.Println("工作结束")
	//	sec超过设置时间就超时
	case <-time.After(time.Duration(sec) * time.Second):
		close(c)
		FuncName("timeout...")
		return
	}
}

自定义处理超时

// @program : r 函数名 timeOut:超时执行的函数,sec同上
func (t *Timer) Run2(r func(arg interface{}),timeOut func(),sec uint64)  {
	c := make(chan struct{})
	go func() {
		// 模拟程序运行了3秒
		//time.Sleep(3 * time.Second)
		r(t.Arg)
		c <- struct{}{}
	}()

	select {
		case <- c:
		return
	case <-time.After(time.Duration(sec) * time.Second):
		close(c)
		timeOut()
		return
	}
}

小例子1:

func foo(a interface{}){
	println(a)
}
func timeOut(){
	println("超时。")
}
func main()  {
	FuncName(n)
	timer := Timer{}
	// 设置超时时间为1秒
	timer.Run2(foo, timeOut,1)
}

2

func input()  {
	fmt.Println("你今年多大了?how old are you.")
	var s string
	_, _ = fmt.Scanln(&s)
	fmt.Println("I'm "+s+" year old")
}
func main() {
	timer := co.Timer{}
	timer.Run2(input, timeOut,3)
}

缺陷就是执行的函数传参麻烦 over.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值