gracelful shutdown

package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "sync"
    "syscall"
    "time"
)

func main() {
    var wg sync.WaitGroup
    ctx, cancel := context.WithCancel(context.Background())

    // Start your application logic here
    // ...

    // Handle graceful shutdown
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-sigCh
        fmt.Println("\nReceived signal to gracefully shutdown. Waiting for tasks to finish...")
        cancel()
    }()

    // Example: Simulate some background tasks
    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            select {
            case <-ctx.Done():
                fmt.Println("Background task: Shutting down gracefully...")
                return
            default:
                // Simulate some work
                fmt.Println("Background task: Performing work...")
                time.Sleep(time.Second)
            }
        }
    }()

    // Wait for all goroutines to finish before exiting
    wg.Wait()
    fmt.Println("All tasks completed. Exiting.")
}