job

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2023 License: MIT Imports: 3 Imported by: 10

README

job

job will be auto restared using Panic_Redo type
!!important : Don't write your own go-routine inside job function
example

package main

import (
	"context"
	"log"
	"time"

	"github.com/coreservice-io/job"
)

// func div(a, b int) int {
// 	return a / b
// }

func main() {

	job_ctx, job_cancel := context.WithCancel(context.Background())

	my_data_counter := 0
	// start a loop job
	err := job.Start(
		job_ctx,
		"job name",
		// job type
		// job.TYPE_PANIC_REDO  auto restart if panic
		// job.TYPE_PANIC_RETURN  stop if panic
		job.TYPE_PANIC_REDO,
		// job interval in seconds
		1,
		//define you data here ,can be anything
		&my_data_counter,
		// check before proces fn , the job will stop running if return false
		// the job will bypass if function is nil
		func(job *job.Job) bool {
			return true
		},
		// job process
		func(j *job.Job) {

			log.Println("count", *j.Data.(*int))
			log.Println("cycle", j.Cycles)
			*j.Data.(*int)++
			//trigger example panic here
			// if j.Cycles == 6 {
			// 	div(0, 0)
			// }
		},
		// onPanic callback, run if panic happened
		func(j *job.Job, err interface{}) {
			log.Println("panic catch", err)
			time.Sleep(5 * time.Second)
		},
		// onFinal callback
		func(j *job.Job) {
			log.Println("finish", "cycle", j.Cycles)
		},
	)

	if err != nil {
		panic(err)
	}

	// if you want to stop job, use job.SetToCancel()
	// after the job finish the current loop it will quit and call the finalFn function
	go func() {
		time.Sleep(20 * time.Second)
		job_cancel()
	}()

	time.Sleep(1 * time.Hour)
}


Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Start

func Start(job_ctx_ context.Context, job_conf JobConfig, data interface{}) error

intervalSecs will be replaced with 1 if <=0

Types

type Job

type Job struct {
	//manual init data
	Name     string
	Interval int64
	JobType  JobType

	//update data in running
	CreateTime    int64
	LastRuntime   int64
	Cycles        int64
	LastPanicTime int64
	PanicCount    int64

	Data interface{}
	// contains filtered or unexported fields
}

type JobConfig added in v0.4.0

type JobConfig struct {
	Name                string
	Job_type            JobType
	Interval_secs       int64
	Chk_before_start_fn func(*Job) bool
	Process_fn          func(*Job)
	On_panic            func(job *Job, panic_err interface{})
	Panic_sleep_secs    int64 //how long to sleep before next panic redo
	Final_fn            func(*Job)
}

type JobType

type JobType string
const (
	TYPE_PANIC_REDO   JobType = "panic_redo"
	TYPE_PANIC_RETURN JobType = "panic_return"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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