Skip to content

Instantly share code, notes, and snippets.

@emrekasg
Created November 16, 2022 10:56
Show Gist options
  • Save emrekasg/dcb96d69df56c2a831efcf890f9d173b to your computer and use it in GitHub Desktop.
Save emrekasg/dcb96d69df56c2a831efcf890f9d173b to your computer and use it in GitHub Desktop.
package workers
import (
"context"
"fmt"
"time"
)
type Worker struct {
Name string
ScheduleTime time.Duration
CancelFunc *context.CancelFunc
Function func(interface{})
}
var (
workers = make(map[string]Worker)
workerChan = make(chan Worker)
)
func RegisterPeriodically(name string, duration time.Duration, handler func(x interface{})) {
worker := Worker{Name: name, ScheduleTime: duration, Function: handler}
workerChan <- worker
}
func Deregister(name string) {
for workerName, _ := range workers {
if workerName == name {
fmt.Println("Stopping worker: ", workerName)
(*workers[workerName].CancelFunc)()
}
}
}
func RunWithContext(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Stopping workers")
return
case worker := <-workerChan:
fmt.Println("Starting worker: ", worker.Name)
ctx, cancel := context.WithCancel(context.Background())
worker.CancelFunc = &cancel
workers[worker.Name] = worker
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("Stopping worker: ", worker.Name)
return
default:
time.Sleep(worker.ScheduleTime)
worker.Function(nil)
}
}
}()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment