runnergroup

package module
v0.0.0-...-408dc58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2023 License: MIT Imports: 2 Imported by: 23

README

RunnerGroup

GoDoc

RunnerGroup is like sync.WaitGroup, the diffrence is if one task stops, all will be stopped.

❤️ A project by txthinking.com

Install

$ go get github.com/txthinking/runnergroup

Example

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/txthinking/runnergroup"
)

func Example() {
	g := runnergroup.New()

	s := &http.Server{
		Addr: ":9991",
	}
	g.Add(&runnergroup.Runner{
		Start: func() error {
			return s.ListenAndServe()
		},
		Stop: func() error {
			return s.Shutdown(context.Background())
		},
	})

	s1 := &http.Server{
		Addr: ":9992",
	}
	g.Add(&runnergroup.Runner{
		Start: func() error {
			return s1.ListenAndServe()
		},
		Stop: func() error {
			return s1.Shutdown(context.Background())
		},
	})

	go func() {
		time.Sleep(5 * time.Second)
		log.Println(g.Done())
	}()
	log.Println(g.Wait())
	// Output:
}

License

Licensed under The MIT License

Documentation

Overview

Example
package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/txthinking/runnergroup"
)

func main() {
	g := runnergroup.New()

	s := &http.Server{
		Addr: ":9991",
	}
	g.Add(&runnergroup.Runner{
		Start: func() error {
			return s.ListenAndServe()
		},
		Stop: func() error {
			return s.Shutdown(context.Background())
		},
	})

	s1 := &http.Server{
		Addr: ":9992",
	}
	g.Add(&runnergroup.Runner{
		Start: func() error {
			return s1.ListenAndServe()
		},
		Stop: func() error {
			return s1.Shutdown(context.Background())
		},
	})

	go func() {
		time.Sleep(5 * time.Second)
		log.Println(g.Done())
	}()
	log.Println(g.Wait())
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Runner

type Runner struct {
	// Start is a blocking function.
	Start func() error
	// Stop is not a blocking function, if Stop called, must let Start return.
	// Notice: Stop maybe called multi times even if before start.
	Stop func() error
	// contains filtered or unexported fields
}

type RunnerGroup

type RunnerGroup struct {
	Runners []*Runner
	End     chan byte
}

RunnerGroup is like sync.WaitGroup, the diffrence is if one task stops, all will be stopped.

func New

func New() *RunnerGroup

func (*RunnerGroup) Add

func (g *RunnerGroup) Add(r *Runner)

func (*RunnerGroup) Done

func (g *RunnerGroup) Done() error

Call Done if you want to stop all. return the stop's return which is not nil, do not guarantee, because starts may ended caused by itself.

func (*RunnerGroup) Wait

func (g *RunnerGroup) Wait() error

Call Wait after all task have been added, Return the first ended start's result.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL