Documentation
¶
Overview ¶
Example ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/pior/runnable"
)
func NewJobs() *Jobs {
return &Jobs{queue: make(chan string)}
}
type Jobs struct {
queue chan string
}
func (s *Jobs) Perform(id string) {
s.queue <- id
}
// Run executes enqueued jobs, drains the queue and quits.
func (s *Jobs) Run(ctx context.Context) error {
for {
select {
case id := <-s.queue:
fmt.Printf("Starting job %s\n", id)
time.Sleep(time.Second)
fmt.Printf("Completed job %s\n", id)
default:
if err := ctx.Err(); err != nil {
close(s.queue)
return err
}
}
}
}
type CleanupTask struct{}
func (*CleanupTask) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
func main() {
runnable.SetLogger(log.New(os.Stdout, "", 0))
g := runnable.NewManager()
jobs := NewJobs()
g.Add(jobs)
server := &http.Server{
Addr: "127.0.0.1:8080",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
jobs.Perform(id)
}),
}
g.Add(runnable.HTTPServer(server), jobs)
task := runnable.Func(func(ctx context.Context) error {
_, _ = http.Post("http://127.0.0.1:8080/?id=1", "test/plain", nil)
_, _ = http.Post("http://127.0.0.1:8080/?id=2", "test/plain", nil)
_, _ = http.Post("http://127.0.0.1:8080/?id=3", "test/plain", nil)
return nil // quit right away, will trigger a shutdown
})
g.Add(task)
cleanup := runnable.Every(&CleanupTask{}, time.Hour)
g.Add(cleanup, jobs)
runnable.Run(g.Build())
// INFO manager: runnable_test.Jobs started
// INFO manager: runnable.httpServer started
// INFO manager: func(runnable.RunnableFunc) started
// INFO manager: periodic(runnable_test.CleanupTask) started
// DBUG http_server: listening
// Starting job 1
// Completed job 1
// Starting job 2
// Completed job 2
// Starting job 3
// INFO manager: starting shutdown (func(runnable.RunnableFunc) died)
// INFO manager: runnable.httpServer cancelled
// INFO manager: func(runnable.RunnableFunc) cancelled
// INFO manager: periodic(runnable_test.CleanupTask) cancelled
// INFO manager: func(runnable.RunnableFunc) stopped
// INFO manager: periodic(runnable_test.CleanupTask) stopped
// DBUG http_server: shutdown (context cancelled)
// INFO manager: runnable.httpServer stopped
// INFO manager: runnable_test.Jobs cancelled
// Completed job 3
// INFO manager: runnable_test.Jobs stopped
// INFO manager: shutdown complete
}
Output:
Index ¶
- func ContextValues(parent context.Context) context.Context
- func Run(runner Runnable)
- func RunFunc(fn RunnableFunc)
- func RunGroup(runners ...Runnable)
- func SetLogger(l Logger)
- type AppManager
- type CloserOptions
- type Logger
- type ManagerOption
- type PanicError
- type RecoverRunner
- type RestartOption
- type Runnable
- func Closer(object io.Closer, opts *CloserOptions) Runnable
- func Every(runnable Runnable, period time.Duration) Runnable
- func Func(fn RunnableFunc) Runnable
- func HTTPServer(server *http.Server) Runnable
- func Recover(runnable Runnable) Runnable
- func Restart(runnable Runnable, opts ...RestartOption) Runnable
- func Signal(runnable Runnable, signals ...os.Signal) Runnable
- type RunnableError
- type RunnableFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextValues ¶ added in v0.10.0
ContextValues returns a new context.Context with the values from the parent, without propagating the cancellation. Useful when you want to protect an operation that should not be cancelled. Often used with context.WithTimeout() or context.WithDeadline().
func Run ¶ added in v0.4.0
func Run(runner Runnable)
Run runs a single runnable, and listen to SIGTERM/SIGINT
func RunFunc ¶ added in v0.5.0
func RunFunc(fn RunnableFunc)
RunFunc runs a runnable function, and listen to SIGTERM/SIGINT
Types ¶
type AppManager ¶ added in v0.11.0
func NewManager ¶ added in v0.11.0
func NewManager(opts ...ManagerOption) AppManager
NewManager returns a runnable that execute runnables in go routines. Runnables can declare a dependency on another runnable. Dependencies are started first and stopped last.
type CloserOptions ¶ added in v0.4.0
CloserOptions configures the behavior of a Closer runnable.
type ManagerOption ¶ added in v0.11.0
type ManagerOption func(*manager)
ManagerOption configures the behavior of a Manager.
func ManagerShutdownTimeout ¶ added in v0.11.0
func ManagerShutdownTimeout(dur time.Duration) ManagerOption
type PanicError ¶
type PanicError struct {
// contains filtered or unexported fields
}
func (*PanicError) Error ¶
func (e *PanicError) Error() string
func (*PanicError) Unwrap ¶
func (e *PanicError) Unwrap() error
type RecoverRunner ¶
type RecoverRunner struct {
// contains filtered or unexported fields
}
type RestartOption ¶ added in v0.6.0
type RestartOption func(*restartConfig)
func RestartCrashDelayFn ¶ added in v0.6.0
func RestartCrashDelayFn(fn func(int) time.Duration) RestartOption
RestartCrashDelayFn sets the function that determine the backoff delay after a crash.
func RestartCrashLimit ¶ added in v0.6.0
func RestartCrashLimit(times int) RestartOption
RestartCrashLimit sets a limit on the number restart after a crash.
func RestartDelay ¶ added in v0.6.0
func RestartDelay(times time.Duration) RestartOption
RestartDelay sets the time waited before restarting the runnable after a successful execution.
func RestartLimit ¶ added in v0.6.0
func RestartLimit(times int) RestartOption
RestartLimit sets a limit on the number of restart after successful execution.
type Runnable ¶
Runnable is the contract for anything that runs with a Go context, respects the concellation contract, and expects the caller to handle errors.
func Closer ¶ added in v0.4.0
func Closer(object io.Closer, opts *CloserOptions) Runnable
Closer returns a runnable that will close what is passed in argument.
func Every ¶ added in v0.11.0
Every returns a runnable that will periodically run the runnable passed in argument.
func Func ¶ added in v0.5.0
func Func(fn RunnableFunc) Runnable
func HTTPServer ¶ added in v0.3.0
HTTPServer returns a runnable that runs a *http.Server.
Example ¶
package main
import (
"context"
stdlog "log"
"net/http"
"os"
"time"
"github.com/pior/runnable"
)
func main() {
runnable.SetLogger(stdlog.New(os.Stdout, "", 0))
server := &http.Server{
Addr: "127.0.0.1:8080",
Handler: http.NotFoundHandler(),
}
r := runnable.HTTPServer(server)
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Millisecond*100)
defer cancel()
_ = r.Run(ctx)
}
Output: http_server: listening on 127.0.0.1:8080 http_server: shutdown
Example (Error) ¶
package main
import (
"context"
stdlog "log"
"net/http"
"os"
"time"
"github.com/pior/runnable"
)
func main() {
runnable.SetLogger(stdlog.New(os.Stdout, "", 0))
server := &http.Server{
Addr: "INVALID",
Handler: http.NotFoundHandler(),
}
r := runnable.HTTPServer(server)
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Millisecond*1000)
defer cancel()
_ = r.Run(ctx)
}
Output: http_server: listening on INVALID http_server: shutdown (err: listen tcp: address INVALID: missing port in address)
func Recover ¶
Recover returns a runnable that recovers when a runnable panics and return an error to represent this panic.
func Restart ¶
func Restart(runnable Runnable, opts ...RestartOption) Runnable
Restart returns a runnable that runs a runnable and restarts it when it fails, with some conditions.
type RunnableError ¶ added in v0.4.0
type RunnableError struct {
// contains filtered or unexported fields
}
func (*RunnableError) Error ¶ added in v0.4.0
func (e *RunnableError) Error() string
func (*RunnableError) Unwrap ¶ added in v0.4.0
func (e *RunnableError) Unwrap() error