-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
51 lines (42 loc) · 1.07 KB
/
main.go
File metadata and controls
51 lines (42 loc) · 1.07 KB
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
package main
import (
"context"
"fmt"
"time"
"github.com/aretw0/lifecycle"
)
func main() {
// 1. Wrap your application logic in a Job
// lifecycle.Run handles:
// - Signal listening (Ctrl+C, SIGTERM)
// - Context cancellation
// - Waiting for background tasks
err := lifecycle.Run(lifecycle.Job(run))
if err != nil {
fmt.Printf("Error: %v\n", err)
}
}
func run(ctx context.Context) error {
fmt.Println("Application started. Press Ctrl+C to exit.")
// 2. Use lifecycle.Go for background tasks
// This ensures the goroutine is tracked and waited for on shutdown.
lifecycle.Go(ctx, func(ctx context.Context) error {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
fmt.Println("Background task stopping...")
return nil
case t := <-ticker.C:
fmt.Printf("Tick: %v\n", t.Format(time.TimeOnly))
}
}
})
// 3. Block until context is cancelled (by signal)
<-ctx.Done()
fmt.Println("Main context cancelled. Cleaning up...")
// Simulate brief cleanup
time.Sleep(500 * time.Millisecond)
return nil
}