Scheduler implementation
This commit is contained in:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user