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
35
36
37
38
39
40
41
42
43
func (p *Pool) PrintStat(sec int) {
	go func() {
		for {
			<-time.After(time.Second * time.Duration(sec))

			s := ""
			for _, i := range p.items {
				s += i.GetStat() + "; "
			}
			log.Printf("Z_QUIT: %s", s)
		}
	}()
Vladimir Barsukov's avatar
Vladimir Barsukov committed
44
45
46
}

func (p *Pool) Wait() {
Vladimir Barsukov's avatar
fix    
Vladimir Barsukov committed
47
48
49
50
	for _, i := range p.items {
		i.Shutdown()
	}

Vladimir Barsukov's avatar
Vladimir Barsukov committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
	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()
	}

	p.Wait()
	time.Sleep(p.PostWaitDur)

	if post != nil {
		post()
	}
}

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