1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
job.go 2.31 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-11-03 20:49 . pool
package scheduler
import (
"fmt"
"gitee.com/h79/goutils/common/system"
"gitee.com/h79/goutils/common/timer"
"time"
)
type JobFunc func(jData interface{}) (interface{}, error)
var _ Task = (*Job)(nil)
type Job struct {
JId string
JState State
JFunc JobFunc
JData interface{} //自定认数据
JTimeout time.Duration
JStartAt int64
}
type JobResult struct {
JId string
Result interface{}
Err error
}
type ShellJob struct {
Job
Cmd string
Result system.CmdResult
}
func NewShellJob(cmd string) *ShellJob {
return &ShellJob{
Job: BuildJob(fmt.Sprintf("ShellJob: Cmd:%s", cmd), 0),
Cmd: cmd,
}
}
func (job *ShellJob) Execute() State {
if job.JState.IsQuit() {
return job.JState
}
if job.JState == InitState {
job.JState = RunningState
}
job.Result = system.SyncExec(job.Cmd, job.JTimeout)
if job.Result.Err != nil {
return ErrorState
}
return CompletedState
}
func BuildJob(jobId string, timeout time.Duration) Job {
return Job{
JId: jobId,
JState: InitState,
JStartAt: timer.CurrentS(),
JTimeout: timeout,
}
}
func NewJob(jobId string, timeout time.Duration) *Job {
job := BuildJob(jobId, timeout)
return &job
}
func (job *Job) WithCall(fn JobFunc) *Job {
job.JFunc = fn
return job
}
func (job *Job) WithTimeOut(timeout time.Duration) *Job {
job.JTimeout = timeout
return job
}
func (job *Job) WithData(data interface{}) *Job {
job.JData = data
return job
}
func (job *Job) GetKey() string {
return job.JId
}
func (job *Job) GetState() State {
return job.JState
}
func (job *Job) Execute() State {
if job.JState.IsQuit() {
return job.JState
}
if job.JState == InitState {
job.JState = RunningState
}
if job.JFunc == nil {
job.JState = CompletedState
return job.JState
}
if _, err := job.JFunc(job.JData); err != nil {
if s, ok := err.(State); ok {
return s
}
job.JState = ErrorState
}
return job.JState
}
func (job *Job) Cancel() {
job.JState = CancelState
}
func (job *Job) Pause() {
job.JState = PauseState
}
func (job *Job) Start() {
job.JState = RunningState
}
func (job *Job) IsQuit() bool {
return job.JState.IsQuit()
}
func (job *Job) CheckTimeout() bool {
if job.JTimeout <= 0 {
return false
}
now := timer.CurrentS()
if job.JStartAt <= 0 {
job.JStartAt = now
}
return now-job.JStartAt > int64(job.JTimeout.Seconds())
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.3.42

搜索帮助