| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 | package common/**import中必须有git.ikuban.com/server/kratos-utils/commonimport (	"context"	"fmt"	"time"	"git.ikuban.com/server/kratos-utils/common")func main() {	test()	go test()	common.GlobalWaitGroup.Stop()}func test() {	ok := common.GlobalWaitGroup.Add(1)	if !ok {		return	}	common.GlobalWaitGroup.SetTimeout(time.Now().Unix() + 12)	go func() {		fmt.Println("任务开始")		time.Sleep(time.Second * 11)		fmt.Println("任务完成")		common.GlobalWaitGroup.Done()	}()}*/import (	"fmt"	"sync"	"time")var GlobalWaitGroup *globalWaitGroupfunc init() {	GlobalWaitGroup = NewGlobalWaitGroup()}type globalWaitGroup struct {	wg      sync.WaitGroup	timeout int64 //超时时间, 时间戳	isStop  bool	lock    sync.Mutex	ok      chan bool}func NewGlobalWaitGroup() *globalWaitGroup {	this := &globalWaitGroup{		wg:     sync.WaitGroup{},		isStop: false,		ok:     make(chan bool, 1),	}	return this}func (this *globalWaitGroup) Stop() {	this.isStop = true	this.Wait()}func (this *globalWaitGroup) Wait() {	go func() {		this.wait()	}()	diff := this.timeout - time.Now().Unix()	if diff <= 0 {		diff = 10	}	select {	case <-this.ok:		fmt.Println("没有任务而结束")		return	case <-time.After(time.Second * time.Duration(diff)):		fmt.Println("超时结束")		return	}}func (this *globalWaitGroup) wait() {	this.wg.Wait()	this.ok <- true}func (this *globalWaitGroup) Done() {	this.wg.Done()}func (this *globalWaitGroup) SetTimeout(timeout int64) {	if timeout <= 0 {		return	}	this.lock.Lock()	if this.timeout < timeout {		this.timeout = timeout	}	this.lock.Unlock()}func (this *globalWaitGroup) Add(delta int) bool {	if this.isStop {		fmt.Println("已结束,不能在添加任务")		return false	}	this.wg.Add(delta)	return true}
 |