| 1 | |
| 2 | package keepawake |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | type State struct { |
| 10 | Active bool `json:"active"` |
| 11 | Error string `json:"error,omitempty"` |
| 12 | } |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | func Run(ctx context.Context, report func(State)) { |
| 18 | run(ctx, report, hold) |
| 19 | } |
| 20 | |
| 21 | func run(ctx context.Context, report func(State), acquire func(context.Context, func()) error) { |
| 22 | var previous State |
| 23 | emit := func(state State) { |
| 24 | if state != previous { |
| 25 | previous = state |
| 26 | report(state) |
| 27 | } |
| 28 | } |
| 29 | delay := time.Second |
| 30 | defer emit(State{}) |
| 31 | for ctx.Err() == nil { |
| 32 | err := acquire(ctx, func() { emit(State{Active: true}); delay = time.Second }) |
| 33 | if ctx.Err() != nil { |
| 34 | return |
| 35 | } |
| 36 | message := "主机防休眠请求已结束" |
| 37 | if err != nil { |
| 38 | message = err.Error() |
| 39 | } |
| 40 | emit(State{Error: message}) |
| 41 | timer := time.NewTimer(delay) |
| 42 | select { |
| 43 | case <-ctx.Done(): |
| 44 | timer.Stop() |
| 45 | return |
| 46 | case <-timer.C: |
| 47 | } |
| 48 | delay = min(30*time.Second, delay*2) |
| 49 | } |
| 50 | } |