gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/lifecycle.v2/runner.go (about) 1 package lifecycle 2 3 type Runner interface { 4 DoStart(Lifecycle) error 5 6 DoRun(Lifecycle) error 7 8 DoClose(Lifecycle) error 9 } 10 11 type nopRunner struct{} 12 13 func (nopRunner) DoStart(Lifecycle) error { return nil } 14 func (nopRunner) DoRun(Lifecycle) error { return nil } 15 func (nopRunner) DoClose(Lifecycle) error { return nil } 16 17 func NopRunner() Runner { return nopRunner{} } 18 19 type ( 20 StartFunc = func(Lifecycle) error 21 RunFunc = func(Lifecycle) error 22 CloseFunc = func(Lifecycle) error 23 ) 24 25 type runnerFunc struct { 26 startFn StartFunc 27 runFn RunFunc 28 closeFn CloseFunc 29 } 30 31 func FuncRunner(startFn, runFn, closeFn func(Lifecycle) error) Runner { 32 if startFn == nil { 33 startFn = func(Lifecycle) error { return nil } 34 } 35 if runFn == nil { 36 runFn = func(Lifecycle) error { return nil } 37 } 38 if closeFn == nil { 39 closeFn = func(Lifecycle) error { return nil } 40 } 41 return runnerFunc{startFn: startFn, runFn: runFn, closeFn: closeFn} 42 } 43 44 func (f runnerFunc) DoStart(lifecycle Lifecycle) error { 45 return f.startFn(lifecycle) 46 } 47 48 func (f runnerFunc) DoRun(lifecycle Lifecycle) error { 49 return f.runFn(lifecycle) 50 } 51 52 func (f runnerFunc) DoClose(lifecycle Lifecycle) error { 53 return f.closeFn(lifecycle) 54 } 55 56 func GetRunner(l Lifecycle) Runner { 57 if runnerGetter, is := l.(interface{ Runner() Runner }); is { 58 return runnerGetter.Runner() 59 } 60 return nil 61 } 62 63 func Interrupted(runner Runner) bool { 64 if interruptedRunner, is := runner.(interface{ Interrupted() bool }); is { 65 return interruptedRunner.Interrupted() 66 } 67 return false 68 }