Skip to content
A graceful way to manage node and goroutines.
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore Initial commit May 15, 2019
.travis.yml 👷 May 15, 2019
LICENSE Initial commit May 15, 2019
README.md 📝 May 21, 2019
go.mod (define interface) May 15, 2019
grace.go ♻️ (re declare log method) May 21, 2019
grace_test.go May 16, 2019

README.md

Grace

Build Status GoDoc Go Report Card

A graceful way to manage node and goroutines. When running, it will listen system signals. After receiving stop signal, the context's cancel function will be called. If all goroutines are exit, node will stop immediately.

Usage

import (
    "log"
    "context"
    "syscall"
    "github.com/beiping96/grace"
)

func main() {
    // Declare stop signals
    // Default is syscall.SIGINT, syscall.SIGQUIT or syscall.SIGTERM
    grace.Init(syscall.SIGQUIT, syscall.SIGTERM)

    // Log declare logger method
    // Default is fmt.Printf
    grace.Log(log.Printf)

    // Register goroutine
    grace.Go(manager0)
    grace.Go(manager1)

    // Never return
    // Stopped when receiving stop signal
    // or all goroutines are exit
    grace.Run()
}

func do(work interface{}) {}

func manager0(ctx context.Context) {
    works := []interface{}{}
    for _, work := range works {
        select {
        case <-ctx.Done():
            // receive stop signal
            return
        default:
        }
        do(work)
    }
}

func manager1(ctx context.Context) {
    works := []interface{}{}
    for _, work := range works {
        select {
        case <-ctx.Done():
            // receive stop signal
            return
        default:
        }
        // start dynamic goroutine
        func(workLocal interface{}) {
            grace.Go(func(ctx context.Context) { do(workLocal) })
        }(work)
    }
}
You can’t perform that action at this time.