forked from vgarvardt/gue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
35 lines (30 loc) · 746 Bytes
/
helpers.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
package gue
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"sync"
"time"
)
// RandomStringID returns random alphanumeric string that can be used as ID.
func RandomStringID() string {
hash := sha256.Sum256([]byte(time.Now().Format(time.RFC3339Nano)))
return hex.EncodeToString(hash[:])[:6]
}
// RunLock ensures that there is only one instance of the running callback function "f" (worker).
func RunLock(ctx context.Context, f func(ctx context.Context) error, mu *sync.Mutex, running *bool, id string) error {
mu.Lock()
if *running {
mu.Unlock()
return fmt.Errorf("worker[id=%s] is already running", id)
}
*running = true
mu.Unlock()
defer func() {
mu.Lock()
*running = false
mu.Unlock()
}()
return f(ctx)
}