forked from linuxdeepin/startdde
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_delay_handler.go
57 lines (49 loc) · 1004 Bytes
/
map_delay_handler.go
1
2
3
4
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"sync"
"time"
)
type mapDelayHandler struct {
task map[string]bool
mutex sync.Mutex
once *sync.Once
delay time.Duration
do func(string)
}
func newMapDelayHandler(delay time.Duration, f func(string)) *mapDelayHandler {
return &mapDelayHandler{
task: make(map[string]bool),
once: &sync.Once{},
do: f,
delay: delay,
}
}
func (dh *mapDelayHandler) AddTask(name string) {
dh.mutex.Lock()
if _, ok := dh.task[name]; ok {
dh.mutex.Unlock()
return
}
dh.task[name] = true
dh.mutex.Unlock()
dh.once.Do(func() {
logger.Debug("first do")
time.AfterFunc(dh.delay, func() {
if dh.do == nil {
return
}
dh.mutex.Lock()
for key := range dh.task {
dh.do(key)
}
//clear dh.task
dh.task = make(map[string]bool)
logger.Debug("new once")
dh.once = &sync.Once{}
dh.mutex.Unlock()
})
})
}