aboutsummaryrefslogtreecommitdiff
path: root/example/policies.go
blob: 6addea74e10e4f704dbb73beabd65680ae492e07 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// +build ignore

package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/neonxp/rutina"
)

func main() {
	// New instance with builtin context
	r := rutina.New()

	r = r.With(rutina.WithErrChan(), rutina.WithStdLogger())

	r.Go(func(ctx context.Context) error {
		<-time.After(1 * time.Second)
		log.Println("Do something 1 second without errors and restart")
		return nil
	}, rutina.RestartIfDone, rutina.ShutdownIfError)

	r.Go(func(ctx context.Context) error {
		<-time.After(2 * time.Second)
		log.Println("Do something 2 seconds without errors and do nothing")
		return nil
	}, rutina.DoNothingIfDone, rutina.ShutdownIfError)

	r.Go(func(ctx context.Context) error {
		<-time.After(3 * time.Second)
		log.Println("Do something 3 seconds with error and restart")
		return errors.New("Error #1!")
	}, rutina.RestartIfError)

	r.Go(func(ctx context.Context) error {
		<-time.After(4 * time.Second)
		log.Println("Do something 4 seconds with error and do nothing")
		return errors.New("Error #2!")
	}, rutina.DoNothingIfError)

	r.Go(func(ctx context.Context) error {
		<-time.After(10 * time.Second)
		log.Println("Do something 10 seconds with error and close context")
		return errors.New("Successfully shutdown at proper place")
	}, rutina.ShutdownIfError)

	r.Go(func(ctx context.Context) error {
		for {
			select {
			case <-ctx.Done():
				log.Println("Shutdown chan listener")
				return nil
			case err := <-r.Errors():
				log.Printf("Error in chan: %v", err)
			}
		}
	})

	// OS signals subscriber
	r.ListenOsSignals()

	if err := r.Wait(); err != nil {
		log.Fatal(err)
	} else {
		log.Println("Routines stopped but not correct")
	}
}