没找到工作 可能是今年最后一更了 😔 直接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
case <- time. After ( time. Duration ( sec) * time. Second) :
close ( c)
FuncName ( "timeout..." )
return
}
}
自定义处理超时
func ( t * Timer) Run2 ( r func ( arg interface { } ) , timeOut func ( ) , sec uint64 ) {
c := make ( chan struct { } )
go func ( ) {
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{ }
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.