aboutsummaryrefslogtreecommitdiff
path: root/example/policies.go
blob: 87081cb3c09c245fca8060deb749bdc19f06f4d2 (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
// +build ignore

package main

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

	"github.com/neonxp/rutina/v3"
)

func main() {
	// New instance with builtin context
	r := rutina.New(rutina.Logger(log.Printf), rutina.ListenOsSignals(os.Interrupt, os.Kill))

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

	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
	})

	r.Go(func(ctx context.Context) error {
		select {
		case <-time.After(time.Second):
			return errors.New("max 10 times")
		case <-ctx.Done():
			return nil
		}
	}, rutina.OnError(rutina.Restart), rutina.MaxCount(10))

	r.Go(func(ctx context.Context) error {
		select {
		case <-time.After(time.Second):
			return errors.New("max 10 seconds")
		case <-ctx.Done():
			return nil
		}
	}, rutina.OnError(rutina.Restart), rutina.SetTimeout(10*time.Second))

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