From b8cfb406ee8a2ffe8248b0c1fa055e65400d5137 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerg=C5=91=20Dulai?= Date: Sun, 4 Oct 2026 23:06:52 +0200 Subject: [PATCH] Scheduler implementation --- scheduler/scheduler.go | 78 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 scheduler/scheduler.go diff --git a/scheduler/scheduler.go b/scheduler/scheduler.go new file mode 100644 index 0000000..9c88d52 --- /dev/null +++ b/scheduler/scheduler.go @@ -0,0 +1,78 @@ +package scheduler + +import ( + "time" + + "github.com/google/uuid" + log "gitlab.com/gdulai/simpleloglvl" +) + +// The main scheduler instance created by default +var mainScheduler *Scheduler + +// Type that can be executed at a certain time. +type Schedulable interface { + Execute(scheduler *Scheduler) +} + +// Describes an item that the scheduler can execute at a given time. +type ScheduleItem struct { + id uuid.UUID + runAt time.Time + schedulable *Schedulable +} + +type Scheduler struct { + scheduled map[uuid.UUID]*ScheduleItem +} + +func InitScheduler() { + mainScheduler = NewScheduler() +} + +// Creates a new scheduler, returns the pointer of it +func NewScheduler() *Scheduler { + schedulr := &Scheduler{scheduled: make(map[uuid.UUID]*ScheduleItem)} + + example := TestSchedule{} + schedulr.Schedule(time.Now().Add(5*time.Second), &example) + + return schedulr +} + +// Schedules an instance of Schedulable. +func (s *Scheduler) Schedule(runAt time.Time, schedulable Schedulable) (uuid.UUID, error) { + newUuid, err := uuid.NewRandom() + if err != nil { + return uuid.UUID{}, err + } + item := &ScheduleItem{id: newUuid, runAt: runAt, schedulable: &schedulable} + s.scheduled[newUuid] = item + + time.AfterFunc(time.Until(runAt), func() { + schedulable.Execute(s) + }) + + return newUuid, nil +} + +// Test schedule which is added when the scheduler is created. +// Used for showing that the scheduler started and working correctly. +type TestSchedule struct { +} + +// Simple Schedulable implementation. +// Logs that the scheduler is running. +func (ex *TestSchedule) Execute(scheduler *Scheduler) { + log.LogInfo("Scheduler running!") +} + +// Scheduled web scraping for news +type ScheduledScraping struct { + Url string +} + +// Returns the refernce of the main scheduler +func MainScheduler() *Scheduler { + return mainScheduler +}