Skip to content

Latest commit

 

History

History
81 lines (55 loc) · 1.59 KB

File metadata and controls

81 lines (55 loc) · 1.59 KB

Build Status codecov Go Report Card

About

This package provides the ability to run background tasks that are performed at the regular intervals.

Install

go get github.com/vxdiv/watcher

Usage

All tasks are marked by the specific composite key in order to enable the process stopping. You must run the watcher before tasks starting or stopping. Only single task can be run with the same composite key.

Simple job

package main

import (
	"fmt"
	"time"

	"github.com/vxdiv/watcher"
)

func main() {

	// Start watcher
	watcher.Run()

	// Start Job in background with interval 3 sec
	watcher.Start(func() {
		fmt.Println("working")
	}, time.Second*3, watcher.CompositeKey{111, "test_1"})

	time.Sleep(time.Second * 10)
	fmt.Println("Done")
}

You can stop job inside job itself or in other place your code even in other package

package main

import (
	"fmt"
	"time"

	"github.com/vxdiv/watcher"
)

func main() {

	watcher.Run()

	watcher.Start(job(0), time.Second*1, watcher.CompositeKey{111, "test_1"})

	time.Sleep(time.Second * 10)
	fmt.Println("Done")
}

func job(c int) watcher.JobFunc {
	count := c
	return func() {
		count++
		fmt.Println(count)
		if count == 5 {
			fmt.Println("job stop")
			watcher.Stop(watcher.CompositeKey{111, "test_1"})
		}
	}
}