Created
November 16, 2022 10:56
-
-
Save emrekasg/dcb96d69df56c2a831efcf890f9d173b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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