Last active
May 6, 2024 12:41
-
-
Save humangrass/bb9e61496ebb38798f28e52c81466425 to your computer and use it in GitHub Desktop.
Handyman - Golang Task Runner | Scheduler Example
This file contains 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 main | |
import ( | |
"fmt" | |
"log" | |
"time" | |
"github.com/robfig/cron" | |
) | |
type Task1 struct { | |
Message string | |
UpdateInterval time.Duration | |
} | |
type Task2 struct { | |
Text string | |
UpdateInterval time.Duration | |
} | |
type Tasks struct { | |
Tasks1 []Task1 | |
Tasks2 []Task2 | |
} | |
func NewTasks() *Tasks { | |
return &Tasks{ | |
Tasks1: []Task1{ | |
{Message: "Message 1 - every 2 sec", UpdateInterval: 2 * time.Second}, | |
{Message: "Message 1 - every 3 sec", UpdateInterval: 3 * time.Second}, | |
{Message: "Message 2 - every 6 sec", UpdateInterval: 6 * time.Second}, | |
}, | |
Tasks2: []Task2{ | |
{Text: "Text 1 - every 2 sec", UpdateInterval: 2 * time.Second}, | |
{Text: "Text 2 - every 4 sec", UpdateInterval: 4 * time.Second}, | |
}, | |
} | |
} | |
type Repository struct { | |
} | |
func NewRepository() *Repository { | |
return &Repository{} | |
} | |
func (r *Repository) OutputFunc(str string) { | |
fmt.Println(str) | |
} | |
type repo interface { | |
OutputFunc(str string) | |
} | |
type Handyman struct { | |
repo repo | |
Tasks *Tasks | |
} | |
func NewHandyman() *Handyman { | |
return &Handyman{ | |
repo: NewRepository(), | |
Tasks: NewTasks(), | |
} | |
} | |
func (h *Handyman) ExecuteTask1(i int) { | |
h.repo.OutputFunc(fmt.Sprintf("Executing Task1: %s", h.Tasks.Tasks1[i].Message)) | |
} | |
func (h *Handyman) ExecuteTask2(i int) { | |
h.repo.OutputFunc(fmt.Sprintf("Executing Task2: %s", h.Tasks.Tasks2[i].Text)) | |
} | |
func main() { | |
handyman := NewHandyman() | |
// Create a new cron scheduler | |
c := cron.New() | |
// Add tasks to the cron scheduler | |
for k, t := range handyman.Tasks.Tasks1 { | |
k := k | |
err := c.AddFunc(fmt.Sprintf("@every %s", t.UpdateInterval), func() { handyman.ExecuteTask1(k) }) | |
if err != nil { | |
log.Print(err) | |
} | |
} | |
for k, t := range handyman.Tasks.Tasks2 { | |
k := k | |
err := c.AddFunc(fmt.Sprintf("@every %s", t.UpdateInterval), func() { handyman.ExecuteTask2(k) }) | |
if err != nil { | |
log.Print(err) | |
} | |
} | |
// Start the cron scheduler | |
c.Start() | |
// Create a channel to receive termination signal | |
done := make(chan struct{}) | |
// Wait for termination signal | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment