控制协程运行时间

控制协程运行时间

May 8, 2024
Go

go控制协程运行时间,使用context.WithTimeout(newCtx, timeout),用recover捕获异常情况

func Go(ctx context.Context, timeout time.Duration, handler func(context.Context)) error {
	oldMsg := codec.Message(ctx)
	newCtx, newMsg := codec.WithNewMessage(detach(ctx))
	codec.CopyMsg(newMsg, oldMsg)
	newCtx, cancel := context.WithTimeout(newCtx, timeout)
	go func() {
		defer func() {
			if e := recover(); e != nil {
				buf := make([]byte, PanicBufLen)
				buf = buf[:runtime.Stack(buf, false)]
				log.Errorf("[PANIC]%v\n%s\n", e, buf)
				report.PanicNum.Incr()
			}
			cancel()
		}()
		handler(newCtx)
	}()
	return nil
}