Skip to content

[WIP] helper to write progs that capable to shutdown gracefully in go

License

Notifications You must be signed in to change notification settings

raohwork/ctxroutines

Repository files navigation

some helpers to write common routines

GoDoc Go Report Card

Work in progress

This library is still WORK IN PROGRESS. Codes here are used in several small projects in production for few months, should be safe I think. But it still need some refinement like writting docs, better test cases and benchmarks.

Graceful shutdown made easy

func myCrawler(ctx context.Context) (err error) {
	req, err := http.NewRequestWithContext(
		ctx, "GET", "https://google.com", nil,
	)
	if err != nil {
		// log the error and
		return err
	}

	data, err := grab(req)
	if err != nil {
		// log the error and
		return
	}

	err = saveDB(ctx, data)
	// log the error and
	return
}

func main() {
	r := Loop( // infinite loop
		RunAtLeast( // do not run crawler too fast
			10*time.Second,
			CTXRunner(myCrawler),
		))

    // cancel og signal, and log the returned error
    log.Print(CancelOnSignal(r, os.Interrupt, os.Kill))
}

Race conditions

Codes in this library are thread-safe unless specified. However, thread-safety of external function is not covered.

Considering this example:

f := Loop(FuncRunner(cancel, yourFunc))

f is thread-safe iff cancel and yourFunc are thread-safe.

License

Copyright Chung-Ping Jen ronmi.ren@gmail.com 2021-

MPL v2.0

About

[WIP] helper to write progs that capable to shutdown gracefully in go

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages