zhangzengfei
2025-02-08 f1c2453aaf74d17048b3f80c08a92e5f69d575e1
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
 
import (
    "context"
    "fmt"
    "log"
    "model-engine/config"
    "model-engine/cron"
    "model-engine/db"
    "model-engine/pkg/logger"
    "os"
    "os/signal"
    "syscall"
)
 
func Init() {
 
    //配置初始化
    config.Init()
 
    // 日志初始化
    logger.Init(*config.LogConf)
    defer logger.Sync()
 
    //数据库初始化
    err := db.Init()
    if err != nil {
        log.Fatalf("Error connecting to the database: %v", err)
    }
 
    //定时任务开启
    if err = cron.Run(); err != nil {
        log.Fatalf("Error Run cron: %v", err)
    }
}
 
// GracefulShutdown listens for OS signals and triggers a cleanup function before exiting.
func GracefulShutdown(ctx context.Context, cleanup func()) {
    // Create a channel to receive the signal.
    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
 
    // Wait for a signal or the provided context to be canceled.
    select {
    case sig := <-sigChan:
        fmt.Printf("Received signal: %v\n", sig)
    case <-ctx.Done():
        fmt.Println("Context was canceled.")
    }
 
    // Perform cleanup operations.
    if cleanup != nil {
        cleanup()
    }
 
    // Stop listening for signals.
    signal.Stop(sigChan)
 
    // Exit the program.
    os.Exit(0)
}
 
// Cleanup handles cleanup tasks before exiting.
func Cleanup() {
    fmt.Println("Cleaning up resources...")
    // Your cleanup code here, such as closing database connections, stopping goroutines, etc.
}
 
func main() {
    // Initialize the application.
    Init()
 
    // Create a background context that can be used to cancel the graceful shutdown.
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
 
    // Start a goroutine to call GracefulShutdown with a cleanup function.
    go GracefulShutdown(ctx, Cleanup)
 
    fmt.Println("Application is running. Press Ctrl+C to exit.")
 
    // Block the main goroutine indefinitely.
    select {}
}