You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
1.0 KiB
84 lines
1.0 KiB
1 year ago
|
package app
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"sync/atomic"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
Idle int32 = iota
|
||
|
Initialized
|
||
|
Starting
|
||
|
Running
|
||
|
Stopping
|
||
|
Stopped
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
// 当前状态
|
||
|
status int32
|
||
|
|
||
|
// 应用上下文
|
||
|
ctx context.Context
|
||
|
exit context.CancelFunc
|
||
|
|
||
|
start func() // 应用启动钩子
|
||
|
stop func() // 应用停止钩子
|
||
|
free func() // 内存释放钩子
|
||
|
)
|
||
|
|
||
|
func initLifecycle() {
|
||
|
ctx, exit = context.WithCancel(context.Background())
|
||
|
|
||
|
start = func() {
|
||
|
// nothing
|
||
|
}
|
||
|
|
||
|
stop = func() {
|
||
|
if exit != nil {
|
||
|
exit()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
free = func() {
|
||
|
ctx = nil
|
||
|
start = nil
|
||
|
stop = nil
|
||
|
exit = nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// setStatus 设置应用状态
|
||
|
func setStatus(newStatus int32) {
|
||
|
atomic.StoreInt32(&status, newStatus)
|
||
|
}
|
||
|
|
||
|
// Status 返回当前状态
|
||
|
func Status() int32 {
|
||
|
return atomic.LoadInt32(&status)
|
||
|
}
|
||
|
|
||
|
func OnStart(fn func()) {
|
||
|
oldStart := start
|
||
|
start = func() {
|
||
|
oldStart()
|
||
|
fn()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func OnStop(fn func()) {
|
||
|
oldStop := stop
|
||
|
stop = func() {
|
||
|
fn()
|
||
|
oldStop()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func OnFree(fn func()) {
|
||
|
oldFree := free
|
||
|
free = func() {
|
||
|
fn()
|
||
|
oldFree()
|
||
|
}
|
||
|
}
|