life

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2020 License: MIT Imports: 6 Imported by: 0

README

life

Documentation

Overview

Package life is a simple place to handle application lifecycle. It assumes there are three phases in an application.

1.) The Init phase (or the setup phase). 2.) The Ready phase 3.) The Defer phase (or the teardown phase).

Consumers should use OnInit, OnReady, and OnDefer to queue tasks for each phase. Once a phase is started, it is locked, and no more tasks can be added to it.

Each phase is handled slightly differently. The Init and Defer phases kick off tasks synchronously; the Ready phase kicks off tasks asynchronously. The Init and Ready phase will abort upon the first failure they encounter; the Defer phase will attempt to execute all tasks, even if there are failures. The Init and Defer phase timeout after 30 seconds; the Ready phase does not have a timeout value. The Ready phase will allow tasks 15 seconds to 'clean up' before transitioning to the next phase.

Index

Examples

Constants

View Source
const (
	Sync syncType = iota
	Async
)

Variables

This section is empty.

Functions

func OnDefer

func OnDefer(f func(context.Context) error)

OnDefer queues a task for the Init phase. OnDefer panics if the init phase has already begun.

func OnInit

func OnInit(f func(context.Context) error)

OnInit queues a task for the Init phase. OnInit panics if the init phase has already begun.

func OnReady

func OnReady(f func(context.Context) error)

OnReady queues a task for the Init phase. OnReady panics if the init phase has already begun.

func Start

func Start(ctx context.Context, logger *log.Logger) error

Start kicks off the queued tasks.

Example

Demonstrates how to queue tasks to execute during various phases of the application's lifecycle.

package main

import (
	"context"
	"fmt"
	"github.com/ajjensen13/life"
	"io/ioutil"
	"log"
	"time"
)

func main() {
	// Queue some initialization work
	life.OnInit(func(ctx context.Context) error {
		fmt.Println("setup complete")

		// Once the initialization work has completed, queue the cleanup work
		defer life.OnDefer(func(ctx context.Context) error {
			fmt.Println("shutdown complete")
			return nil
		})

		// Queue the work to execute during the ready phase when the initialization succeeds
		life.OnReady(func(ctx context.Context) error {
			time.Sleep(time.Second)
			fmt.Println("ready complete")
			return nil
		})
		return nil
	})

	err := life.Start(context.Background(), log.New(ioutil.Discard, log.Prefix(), log.Flags()))
	if err != nil {
		panic(err)
	}
	fmt.Println("program complete")

}
Output:

setup complete
ready complete
shutdown complete
program complete

Types

This section is empty.

Jump to

Keyboard shortcuts

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