1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
run.go 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
package system
import (
"gitee.com/h79/goutils/common/config"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
)
func Run() {
exit := Exit()
for {
select {
case <-exit.Done():
return
case <-Closed():
return
}
}
}
type ExitSig struct {
S chan os.Signal
}
func (c *ExitSig) Done() <-chan os.Signal {
return c.S
}
func Exit() *ExitSig {
e := &ExitSig{S: make(chan os.Signal)}
signal.Notify(e.S, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGQUIT)
return e
}
func Closed() <-chan bool {
return config.Closed()
}
func Closing() {
config.Close()
}
func Quit() {
timeout := time.After(2 * time.Second)
select {
case <-timeout:
return
}
}
type Running struct {
ev *Event
wg sync.WaitGroup
}
var (
mainRan int32 = 0
running *Running
once sync.Once
)
func Go() *Running {
once.Do(func() {
running = NewRunning()
})
return running
}
// NewRunning
// f 是否fire
func NewRunning() *Running {
return &Running{ev: NewEvent()}
}
func ChildRunning(fn func()) {
Go().Run(false, fn)
}
func MainRunning(fn func()) {
if atomic.AddInt32(&mainRan, 1) > 1 {
panic("can not repeat call,only call one")
}
Go().Run(true, func() {
defer atomic.AddInt32(&mainRan, -1)
fn()
})
}
// Run if fire=true, select Running.Done()
func (m *Running) Run(fire bool, fn func()) {
m.wg.Add(1)
go func() {
defer m.wg.Done()
defer Recover()
defer func() {
if !fire {
return
}
m.ev.Fire()
}()
fn()
}()
}
func (m *Running) Done() <-chan struct{} {
return m.ev.Done()
}
func (m *Running) Wait() {
m.wg.Wait()
}
type RunningCheck struct {
rm sync.Mutex
fRun bool
}
func (rc *RunningCheck) IsRunning() bool {
rc.rm.Lock()
defer rc.rm.Unlock()
return rc.fRun
}
func (rc *RunningCheck) TryGoRunning(fn func()) {
rc.rm.Lock()
if rc.fRun {
rc.rm.Unlock()
return
}
rc.fRun = true
rc.rm.Unlock()
ChildRunning(func() {
defer func() {
rc.rm.Lock()
rc.fRun = false
rc.rm.Unlock()
}()
fn()
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.32

搜索帮助