pool.go 1.03 KB
Newer Older
Vladimir Barsukov's avatar
Vladimir Barsukov committed
1
2
3
package zquit

import (
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
4
	"log"
Vladimir Barsukov's avatar
Vladimir Barsukov committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
	"os"
	"os/signal"
	"syscall"
	"time"
)

type Pool struct {
	PostWaitDur time.Duration

	items []*ZQuit
}

func NewPool(postWaitDur time.Duration) *Pool {
	return &Pool{
		PostWaitDur: postWaitDur,
		items:       make([]*ZQuit, 0),
	}
}

func DefaultPool() *Pool {
	return NewPool(time.Second)
}

func (p *Pool) Add(z *ZQuit) {
	p.items = append(p.items, z)
}

Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
32
33
34
func (p *Pool) PrintStat(sec int) {
	go func() {
		for {
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
35
			time.Sleep(time.Second * time.Duration(sec))
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
36
37
38
39
40

			s := ""
			for _, i := range p.items {
				s += i.GetStat() + "; "
			}
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
41
			log.Printf("ZQUIT: %s", s)
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
42
43
		}
	}()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
}

func (p *Pool) Wait() {
	for _, i := range p.items {
		i.Wait()
	}
}

func (p *Pool) WaitInterruptPrePost(pre func(), post func()) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c

	if pre != nil {
		pre()
	}

Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
61
62
63
64
	for _, i := range p.items {
		i.Shutdown()
	}

Vladimir Barsukov's avatar
Vladimir Barsukov committed
65
66
67
68
69
70
71
72
73
74
75
	p.Wait()
	time.Sleep(p.PostWaitDur)

	if post != nil {
		post()
	}
}

func (p *Pool) WaitInterrupt() {
	p.WaitInterruptPrePost(nil, nil)
}