123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package ctrl_v1
- import (
- "gd_gateway/errors"
- "sync"
- "time"
- )
- const (
- NoLock = 0
- DataLock = 1
- TimeLock = 2
- )
- type Result struct {
- Chan chan error
- Data string
- Mutex sync.Mutex
- Flag int
- StartTime int64
- MinimalTimeConsuming int
- }
- func NewResult(startTime int64, minimalTimeConsuming int) Result {
- result := Result{}
- result.Chan = make(chan error, 1)
- result.Flag = NoLock
- result.StartTime = startTime / 1e9
- result.MinimalTimeConsuming = minimalTimeConsuming
- return result
- }
- func CheckDataLock(result *Result) bool {
- result.Mutex.Lock()
- defer result.Mutex.Unlock()
- // 数据业务处理持锁已处理
- if result.Flag == DataLock {
- return true
- } else {
- result.Flag = TimeLock
- return false
- }
- }
- // 如果已被定时任务处理
- func CheckTimeLock(result *Result) bool {
- result.Mutex.Lock()
- defer result.Mutex.Unlock()
- defer CheckMinimalTime(result)
- // 定时任务处理持锁已处理,接口已返回
- if result.Flag == TimeLock {
- return true
- } else {
- result.Flag = DataLock
- return false
- }
- }
- func CheckMinimalTime(result *Result) {
- //fmt.Printf("%+v", result)
- if result.MinimalTimeConsuming > 0 {
- useTime := int(time.Now().Unix() - result.StartTime)
- if useTime < result.MinimalTimeConsuming {
- time.Sleep(time.Duration(result.MinimalTimeConsuming-useTime) * time.Second)
- }
- }
- }
- // 获取结果
- func GetResult(timeOut int64, result *Result) (string, error) {
- defer close(result.Chan)
- if timeOut == 0 {
- for {
- select {
- case err := <-result.Chan:
- if err != nil {
- return "", err
- } else {
- return result.Data, nil
- }
- }
- }
- } else {
- after := time.After(time.Duration(timeOut) * time.Millisecond)
- //after := time.After(time.Duration(timeOut) * time.Second)
- for {
- select {
- case err := <-result.Chan:
- if err != nil {
- return "", err
- } else {
- return result.Data, nil
- }
- case <-after:
- if CheckDataLock(result) {
- err := <-result.Chan
- if err != nil {
- return "", err
- } else {
- return result.Data, nil
- }
- } else {
- return "", errors.NoRecord
- }
- }
- }
- }
- }
|