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 {}
|
}
|