No description, website, or topics provided.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example
.gitignore
.travis.yml
LICENSE
README.md
hellsgate.go
hellsgate_test.go

README.md

hellsgate

Build Status Coverage Status GoDoc

hellsgate

hell's gate is a lib for treating with signals in go

Install

go get -u github.com/deadcheat/hellsgate

Example

package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"syscall"
	"time"

	"github.com/deadcheat/hellsgate"
)

func main() {
	gate := hellsgate.New()
	t := NewTicker(10*time.Second, func() error {
		fmt.Println(time.Now())
		return nil
	})
	gate.AddHandler(syscall.SIGINT, func(c context.Context) error {
		fmt.Println("gimme a hell yeah!")
		t.Stop()
		return nil
	}, context.TODO()).Listen()
	t.Wait()
}

// Ticker Tick Tack
type Ticker struct {
	ticker *time.Ticker
	closer chan bool
	wg     sync.WaitGroup
}

// NewTicker create new Timer executing func
func NewTicker(d time.Duration, f func() error) *Ticker {
	t := Ticker{}
	t.ticker = time.NewTicker(d)
	t.closer = make(chan bool)
	t.wg.Add(1)
	go func() {
		defer t.wg.Done()
		for {
			select {
			case ts := <-t.ticker.C:
				log.Println("ticker execute : ", ts)
				if err := f(); err != nil {
					log.Println(ts, err)
				}
			case <-t.closer:
				return
			}
		}
	}()
	return &t
}

// Wait for inner workgroup
func (t *Ticker) Wait() {
	t.wg.Wait()
}

// Stop stop
func (t *Ticker) Stop() {
	log.Println("Stop ticker")
	t.ticker.Stop()
	close(t.closer)
	t.wg.Wait()
}