1 Star 1 Fork 0

loyalflower/toolkit

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
shutdown.go 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
Niel 提交于 2022-12-30 15:29 +08:00 . feat: 增加系统负载cpu、memory等收集功能
//go:build linux || darwin
// +build linux darwin
package system
import (
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/threading"
)
const (
wrapUpTime = time.Second
// why we use 5500 milliseconds is because most of our queue are blocking mode with 5 seconds
waitTime = 5500 * time.Millisecond
)
var (
wrapUpListeners = new(listenerManager)
shutdownListeners = new(listenerManager)
delayTimeBeforeForceQuit = waitTime
)
// AddShutdownListener adds fn as a shutdown listener.
// The returned func can be used to wait for fn getting called.
func AddShutdownListener(fn func()) (waitForCalled func()) {
return shutdownListeners.addListener(fn)
}
// AddWrapUpListener adds fn as a wrap up listener.
// The returned func can be used to wait for fn getting called.
func AddWrapUpListener(fn func()) (waitForCalled func()) {
return wrapUpListeners.addListener(fn)
}
// SetTimeToForceQuit sets the waiting time before force quitting.
func SetTimeToForceQuit(duration time.Duration) {
delayTimeBeforeForceQuit = duration
}
func gracefulStop(signals chan os.Signal) {
signal.Stop(signals)
go wrapUpListeners.notifyListeners()
time.Sleep(wrapUpTime)
go shutdownListeners.notifyListeners()
time.Sleep(delayTimeBeforeForceQuit - wrapUpTime)
syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
}
type listenerManager struct {
lock sync.Mutex
waitGroup sync.WaitGroup
listeners []func()
}
func (lm *listenerManager) addListener(fn func()) (waitForCalled func()) {
lm.waitGroup.Add(1)
lm.lock.Lock()
lm.listeners = append(lm.listeners, func() {
defer lm.waitGroup.Done()
fn()
})
lm.lock.Unlock()
return func() {
lm.waitGroup.Wait()
}
}
func (lm *listenerManager) notifyListeners() {
lm.lock.Lock()
defer lm.lock.Unlock()
group := threading.NewRoutineGroup()
for _, listener := range lm.listeners {
group.RunSafe(listener)
}
group.Wait()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/loyalflower/toolkit.git
git@gitee.com:loyalflower/toolkit.git
loyalflower
toolkit
toolkit
v1.1.0

搜索帮助