From 85343cd11d2649c567a774043f9c9fa028bc54f5 Mon Sep 17 00:00:00 2001 From: javad Date: Sun, 26 Nov 2023 12:08:07 +0330 Subject: [PATCH] refactor: improve module path --- README.md | 8 +-- _example/multiple/jobs/main.go | 14 ++-- _example/multiple/scheduler/main.go | 19 +++--- _example/sample/main.go | 12 ++-- {schedErrors => errs}/errors.go | 4 +- example_test.go | 17 +++++ go.mod | 2 +- helper/helper.go | 8 +-- job/job.go => job.go | 52 +++++++-------- job/job.partial.go => job.partial.go | 6 +- scheduler.go | 45 +++++++------ scheduler.partial.go | 19 +++--- scheduler_test.go | 99 ++++++++++++++-------------- global/global.go => types/types.go | 2 +- job/units.go => units.go | 16 ++--- 15 files changed, 166 insertions(+), 157 deletions(-) rename {schedErrors => errs}/errors.go (82%) create mode 100644 example_test.go rename job/job.go => job.go (80%) rename job/job.partial.go => job.partial.go (94%) rename global/global.go => types/types.go (93%) rename job/units.go => units.go (89%) diff --git a/README.md b/README.md index 42d8336..da158ca 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # Scheduler -[![Go Reference](https://pkg.go.dev/badge/github.com/Ja7ad/Scheduler.svg)](https://pkg.go.dev/github.com/Ja7ad/Scheduler) +[![Go Reference](https://pkg.go.dev/badge/github.com/Ja7ad/scheduler.svg)](https://pkg.go.dev/github.com/Ja7ad/scheduler) -[Scheduler](https://pkg.go.dev/github.com/Ja7ad/Scheduler) package is a zero-dependency scheduling library for Go +[Scheduler](https://pkg.go.dev/github.com/Ja7ad/scheduler) package is a zero-dependency scheduling library for Go # Install ```console -go get -u github.com/Ja7ad/Scheduler +go get -u github.com/Ja7ad/scheduler ``` # Features @@ -23,7 +23,7 @@ package main import ( "fmt" - "github.com/Ja7ad/Scheduler" + "github.com/Ja7ad/scheduler" ) var ( diff --git a/_example/multiple/jobs/main.go b/_example/multiple/jobs/main.go index a385926..9e92edf 100644 --- a/_example/multiple/jobs/main.go +++ b/_example/multiple/jobs/main.go @@ -2,21 +2,19 @@ package main import ( "fmt" - "github.com/Ja7ad/Scheduler" -) - -var ( - Sched = Scheduler.NewScheduler() + "github.com/Ja7ad/scheduler" ) func main() { - if err := Sched.Every(5).Second().Do(Greeting); err != nil { + sched := scheduler.New() + + if err := sched.Every(5).Second().Do(Greeting); err != nil { panic(err) } - if err := Sched.Every(7).Second().Do(Name, "Javad"); err != nil { + if err := sched.Every(7).Second().Do(Name, "Javad"); err != nil { panic(err) } - <-Sched.Start() + <-sched.Start() } func Greeting() { diff --git a/_example/multiple/scheduler/main.go b/_example/multiple/scheduler/main.go index 6cca66a..b0d7375 100644 --- a/_example/multiple/scheduler/main.go +++ b/_example/multiple/scheduler/main.go @@ -2,12 +2,7 @@ package main import ( "fmt" - "github.com/Ja7ad/Scheduler" -) - -var ( - Sched1 = Scheduler.NewScheduler() - Sched2 = Scheduler.NewScheduler() + "github.com/Ja7ad/scheduler" ) func main() { @@ -16,17 +11,21 @@ func main() { } func sched1() { - if err := Sched1.Every(5).Second().Do(Greeting); err != nil { + sched := scheduler.New() + + if err := sched.Every(5).Second().Do(Greeting); err != nil { panic(err) } - <-Sched1.Start() + <-sched.Start() } func sched2() { - if err := Sched2.Every(10).Second().Do(Name, "Javad"); err != nil { + sched := scheduler.New() + + if err := sched.Every(10).Second().Do(Name, "Javad"); err != nil { panic(err) } - <-Sched2.Start() + <-sched.Start() } func Greeting() { diff --git a/_example/sample/main.go b/_example/sample/main.go index c17a0a2..43ad1df 100644 --- a/_example/sample/main.go +++ b/_example/sample/main.go @@ -2,19 +2,17 @@ package main import ( "fmt" - "github.com/Ja7ad/Scheduler" -) - -var ( - Sched = Scheduler.NewScheduler() + "github.com/Ja7ad/scheduler" ) func main() { - if err := Sched.Every(5).Second().Do(Greeting); err != nil { + sched := scheduler.New() + + if err := sched.Every(5).Second().Do(Greeting); err != nil { panic(err) } - <-Sched.Start() + <-sched.Start() } func Greeting() { diff --git a/schedErrors/errors.go b/errs/errors.go similarity index 82% rename from schedErrors/errors.go rename to errs/errors.go index 7f1c7c6..57a0de0 100644 --- a/schedErrors/errors.go +++ b/errs/errors.go @@ -1,9 +1,9 @@ -package schedErrors +package errs import "errors" var ( - ERROR_TIME_FORMAT = errors.New("schedErrors in time format") + ERROR_TIME_FORMAT = errors.New("errs in time format") ERROR_PARAMETER = errors.New("no parameters are adapted") ERROR_NOT_A_FUNCTION = errors.New("in the job queue, only functions can be scheduled") ERROR_JOB_PREIOD = errors.New("no job period specified") diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..f140b05 --- /dev/null +++ b/example_test.go @@ -0,0 +1,17 @@ +package scheduler + +import "fmt" + +func ExampleNew() { + greetingFunc := func() { + fmt.Println("Hello, World!") + } + + sched := New() + + if err := sched.Every(5).Second().Do(greetingFunc); err != nil { + panic(err) + } + + <-sched.Start() +} diff --git a/go.mod b/go.mod index bfe9e08..f911153 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/Ja7ad/Scheduler +module github.com/Ja7ad/scheduler go 1.17 diff --git a/helper/helper.go b/helper/helper.go index c002737..de0f258 100644 --- a/helper/helper.go +++ b/helper/helper.go @@ -3,7 +3,7 @@ package helper import ( "crypto/sha256" "fmt" - "github.com/Ja7ad/Scheduler/schedErrors" + "github.com/Ja7ad/scheduler/errs" "reflect" "runtime" "strconv" @@ -27,7 +27,7 @@ func GetFunctionName(functionName interface{}) string { func CallJobFuncWithParams(jobFunc interface{}, params []interface{}) ([]reflect.Value, error) { f := reflect.ValueOf(jobFunc) if len(params) != f.Type().NumIn() { - return nil, schedErrors.ERROR_PARAMETER + return nil, errs.ERROR_PARAMETER } in := make([]reflect.Value, len(params)) for k, param := range params { @@ -40,7 +40,7 @@ func CallJobFuncWithParams(jobFunc interface{}, params []interface{}) ([]reflect func TimeFormat(time string) (h, m, s int, err error) { timeSplit := strings.Split(time, ":") if len(timeSplit) < 2 || len(timeSplit) > 3 { - return 0, 0, 0, schedErrors.ERROR_TIME_FORMAT + return 0, 0, 0, errs.ERROR_TIME_FORMAT } if h, err = strconv.Atoi(timeSplit[0]); err != nil { @@ -58,7 +58,7 @@ func TimeFormat(time string) (h, m, s int, err error) { } if h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59 { - return 0, 0, 0, schedErrors.ERROR_TIME_FORMAT + return 0, 0, 0, errs.ERROR_TIME_FORMAT } return h, m, s, nil diff --git a/job/job.go b/job.go similarity index 80% rename from job/job.go rename to job.go index 0c5e3ae..d5fd792 100644 --- a/job/job.go +++ b/job.go @@ -1,17 +1,17 @@ -package job +package scheduler import ( "fmt" - "github.com/Ja7ad/Scheduler/global" - "github.com/Ja7ad/Scheduler/helper" - "github.com/Ja7ad/Scheduler/schedErrors" + "github.com/Ja7ad/scheduler/errs" + "github.com/Ja7ad/scheduler/helper" + "github.com/Ja7ad/scheduler/types" "log" "reflect" "time" ) var ( - JobLocker Locker + jobLocker Locker ) type Locker interface { @@ -25,7 +25,7 @@ type Job struct { Functions map[string]interface{} FuncParams map[string][]interface{} Interval uint64 - JobUnit global.TimeUnit + JobUnit types.TimeUnit Tags []string AtTime time.Duration TimeLocation *time.Location @@ -40,7 +40,7 @@ type Job struct { func NewJob(interval uint64) *Job { return &Job{ Interval: interval, - TimeLocation: global.TimeZone, + TimeLocation: types.TimeZone, LastRun: time.Unix(0, 0), NextRun: time.Unix(0, 0), FirstWeekDay: time.Sunday, @@ -53,16 +53,16 @@ func NewJob(interval uint64) *Job { // Run the job and reschedule it func (j *Job) Run() ([]reflect.Value, error) { if j.LockJob { - if JobLocker == nil { - return nil, fmt.Errorf("%v %v", schedErrors.ERROR_TRY_LOCK_JOB, j.JobFunction) + if jobLocker == nil { + return nil, fmt.Errorf("%v %v", errs.ERROR_TRY_LOCK_JOB, j.JobFunction) } hashedKey := helper.GetFunctionHashedKey(j.JobFunction) - if _, err := JobLocker.Lock(hashedKey); err != nil { - return nil, fmt.Errorf("%v %v", schedErrors.ERROR_TRY_LOCK_JOB, j.JobFunction) + if _, err := jobLocker.Lock(hashedKey); err != nil { + return nil, fmt.Errorf("%v %v", errs.ERROR_TRY_LOCK_JOB, j.JobFunction) } - defer JobLocker.Unlock(hashedKey) + defer jobLocker.Unlock(hashedKey) } result, err := helper.CallJobFuncWithParams(j.Functions[j.JobFunction], j.FuncParams[j.JobFunction]) if err != nil { @@ -80,7 +80,7 @@ func (j *Job) Do(jobFunction interface{}, params ...interface{}) error { jobType := reflect.TypeOf(jobFunction) if jobType.Kind() != reflect.Func { - return schedErrors.ERROR_NOT_A_FUNCTION + return errs.ERROR_NOT_A_FUNCTION } funcName := helper.GetFunctionName(jobFunction) @@ -103,7 +103,7 @@ func (j *Job) DoJobSafely(jobFunction interface{}, params ...interface{}) error recoveryFunction := func() { defer func() { if r := recover(); r != nil { - log.Printf("Internal Panic: %v", r) + log.Printf("internal panic happen: %v", r) } }() _, _ = helper.CallJobFuncWithParams(jobFunction, params) @@ -112,12 +112,13 @@ func (j *Job) DoJobSafely(jobFunction interface{}, params ...interface{}) error } // At schedules the job to run at the given time +// // s.Every(1).Day().At("20:30:01").Do(task) // s.Every(1).Monday().At("20:30:01").Do(task) func (j *Job) At(t string) *Job { h, m, s, err := helper.TimeFormat(t) if err != nil { - j.JobError = schedErrors.ERROR_TIME_FORMAT + j.JobError = errs.ERROR_TIME_FORMAT return j } j.AtTime = time.Duration(h)*time.Hour + time.Duration(m)*time.Minute + time.Duration(s)*time.Second @@ -137,12 +138,12 @@ func (j *Job) NextJobRun() error { } switch j.JobUnit { - case global.Seconds, global.Minutes, global.Hours: + case types.Seconds, types.Minutes, types.Hours: j.NextRun = j.LastRun.Add(periodDuration) - case global.Days: + case types.Days: j.NextRun = j.RoundToMidNight(j.LastRun) j.NextRun = j.NextRun.Add(j.AtTime) - case global.Weeks: + case types.Weeks: j.NextRun = j.RoundToMidNight(j.LastRun) dayDiff := int(j.FirstWeekDay) dayDiff -= int(j.NextRun.Weekday()) @@ -150,7 +151,6 @@ func (j *Job) NextJobRun() error { j.NextRun = j.NextRun.Add(time.Duration(dayDiff) * 24 * time.Hour) } j.NextRun = j.NextRun.Add(j.AtTime) - // TODO: Add support for months } // next possible schedule advance @@ -166,20 +166,20 @@ func (j *Job) PeriodDuration() (time.Duration, error) { var periodDuration time.Duration switch j.JobUnit { - case global.Seconds: + case types.Seconds: periodDuration = interval * time.Second - case global.Minutes: + case types.Minutes: periodDuration = interval * time.Minute - case global.Hours: + case types.Hours: periodDuration = interval * time.Hour - case global.Days: + case types.Days: periodDuration = interval * time.Hour * 24 - case global.Weeks: + case types.Weeks: periodDuration = interval * time.Hour * 24 * 7 - case global.Months: + case types.Months: periodDuration = interval * time.Hour * 24 * 30 default: - return 0, schedErrors.ERROR_JOB_PREIOD + return 0, errs.ERROR_JOB_PREIOD } return periodDuration, nil } diff --git a/job/job.partial.go b/job.partial.go similarity index 94% rename from job/job.partial.go rename to job.partial.go index 688e656..51e4980 100644 --- a/job/job.partial.go +++ b/job.partial.go @@ -1,8 +1,8 @@ -package job +package scheduler import ( "fmt" - "github.com/Ja7ad/Scheduler/global" + "github.com/Ja7ad/scheduler/types" "time" ) @@ -45,7 +45,7 @@ func (j *Job) From(t *time.Time) *Job { } // SetJobUnit sets the JobUnit -func (j *Job) SetJobUnit(unit global.TimeUnit) *Job { +func (j *Job) SetJobUnit(unit types.TimeUnit) *Job { j.JobUnit = unit return j } diff --git a/scheduler.go b/scheduler.go index e42bd6d..8fa44f2 100644 --- a/scheduler.go +++ b/scheduler.go @@ -1,35 +1,34 @@ -package Scheduler +package scheduler import ( - "github.com/Ja7ad/Scheduler/global" - "github.com/Ja7ad/Scheduler/helper" - "github.com/Ja7ad/Scheduler/job" + "github.com/Ja7ad/scheduler/helper" + "github.com/Ja7ad/scheduler/types" "sort" "time" ) var ( - defaultScheduler = NewScheduler() + defaultScheduler = New() ) // Scheduler is the main struct of the scheduler type Scheduler struct { - JobList [global.MaxJobs]*job.Job // Jobs is the array of jobs - JobSize int // JobSize is the number of jobs - Location *time.Location // Location is the location of the scheduler + JobList [types.MaxJobs]*Job // Jobs is the array of jobs + JobSize int // JobSize is the number of jobs + Location *time.Location // Location is the location of the scheduler } -// NewScheduler creates a new scheduler -func NewScheduler() *Scheduler { +// New creates a new scheduler +func New() *Scheduler { return &Scheduler{ - JobList: [global.MaxJobs]*job.Job{}, + JobList: [types.MaxJobs]*Job{}, JobSize: 0, - Location: global.TimeZone, + Location: types.TimeZone, } } // Jobs returns list of jobs from scheduler -func (s *Scheduler) Jobs() []*job.Job { +func (s *Scheduler) Jobs() []*Job { return s.JobList[:s.JobSize] } @@ -54,8 +53,8 @@ func (s *Scheduler) ChangeLocation(newLocation *time.Location) { } // GetRunnableJobs returns a list of jobs that are ready to run -func (s *Scheduler) GetRunnableJobs() (runningJobs [global.MaxJobs]*job.Job, n int) { - runnableJobs := [global.MaxJobs]*job.Job{} +func (s *Scheduler) GetRunnableJobs() (runningJobs [types.MaxJobs]*Job, n int) { + runnableJobs := [types.MaxJobs]*Job{} n = 0 sort.Sort(s) for i := 0; i < s.JobSize; i++ { @@ -70,7 +69,7 @@ func (s *Scheduler) GetRunnableJobs() (runningJobs [global.MaxJobs]*job.Job, n i } // NextRun returns the next run time of the job at index i -func (s *Scheduler) NextRun() (*job.Job, time.Time) { +func (s *Scheduler) NextRun() (*Job, time.Time) { if s.JobSize <= 0 { return nil, time.Now() } @@ -79,8 +78,8 @@ func (s *Scheduler) NextRun() (*job.Job, time.Time) { } // Every schedules a new job to run every duration -func (s *Scheduler) Every(interval uint64) *job.Job { - j := job.NewJob(interval).Location(s.Location) +func (s *Scheduler) Every(interval uint64) *Job { + j := NewJob(interval).Location(s.Location) s.JobList[s.JobSize] = j s.JobSize++ return j @@ -116,21 +115,21 @@ func (s *Scheduler) RunAllWithDelay(d int) { // Remove job by function func (s *Scheduler) Remove(j interface{}) { - s.RemoveByCondition(func(someJob *job.Job) bool { + s.RemoveByCondition(func(someJob *Job) bool { return someJob.JobFunction == helper.GetFunctionName(j) }) } // RemoveByRef removes specific job j by reference -func (s *Scheduler) RemoveByRef(j *job.Job) { - s.RemoveByCondition(func(someJob *job.Job) bool { +func (s *Scheduler) RemoveByRef(j *Job) { + s.RemoveByCondition(func(someJob *Job) bool { return someJob == j }) } // RemoveByTag removes specific job j by tag func (s *Scheduler) RemoveByTag(t string) { - s.RemoveByCondition(func(someJob *job.Job) bool { + s.RemoveByCondition(func(someJob *Job) bool { for _, a := range someJob.Tags { if a == t { return true @@ -141,7 +140,7 @@ func (s *Scheduler) RemoveByTag(t string) { } // RemoveByCondition removes specific job j by condition -func (s *Scheduler) RemoveByCondition(remove func(*job.Job) bool) { +func (s *Scheduler) RemoveByCondition(remove func(*Job) bool) { i := 0 // Delete jobs until no more match the criteria diff --git a/scheduler.partial.go b/scheduler.partial.go index 7d7570a..0a2102b 100644 --- a/scheduler.partial.go +++ b/scheduler.partial.go @@ -1,14 +1,13 @@ -package Scheduler +package scheduler import ( - "github.com/Ja7ad/Scheduler/global" - "github.com/Ja7ad/Scheduler/helper" - "github.com/Ja7ad/Scheduler/job" + "github.com/Ja7ad/scheduler/helper" + "github.com/Ja7ad/scheduler/types" "time" ) // Every schedules a new periodic job running in specific interval -func Every(interval uint64) *job.Job { +func Every(interval uint64) *Job { return defaultScheduler.Every(interval) } @@ -44,7 +43,7 @@ func Remove(j interface{}) { // ChangeTimeLocation change the location of a time func ChangeTimeLocation(location *time.Location) { - global.TimeZone = location + types.TimeZone = location defaultScheduler.ChangeLocation(location) } @@ -59,16 +58,16 @@ func Scheduled(j interface{}) bool { } // NextRun gets the next running time -func NextRun() (job *job.Job, time time.Time) { +func NextRun() (job *Job, time time.Time) { return defaultScheduler.NextRun() } // Jobs returns the list of job from the defaultScheduler -func Jobs() []*job.Job { +func Jobs() []*Job { return defaultScheduler.Jobs() } // SetLocker sets a locker implementation -func SetLocker(l job.Locker) { - job.JobLocker = l +func SetLocker(l Locker) { + jobLocker = l } diff --git a/scheduler_test.go b/scheduler_test.go index d74a09c..0f6cb60 100644 --- a/scheduler_test.go +++ b/scheduler_test.go @@ -1,10 +1,9 @@ -package Scheduler +package scheduler import ( "fmt" - "github.com/Ja7ad/Scheduler/global" - "github.com/Ja7ad/Scheduler/helper" - "github.com/Ja7ad/Scheduler/job" + "github.com/Ja7ad/scheduler/helper" + "github.com/Ja7ad/scheduler/types" "github.com/stretchr/testify/assert" "log" "sync" @@ -21,18 +20,18 @@ func taskWithParams(a int, b string) { } func TestSecond(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() jb := scheduler.Every(1).Seconds() testJobWithInterval(t, scheduler, jb, 1) } func TestSeconds(t *testing.T) { - sched := NewScheduler() + sched := New() jb := sched.Every(2).Seconds() testJobWithInterval(t, sched, jb, 2) } -func testJobWithInterval(t *testing.T, sched *Scheduler, jb *job.Job, expectedTimeBetweenRuns int64) { +func testJobWithInterval(t *testing.T, sched *Scheduler, jb *Job, expectedTimeBetweenRuns int64) { jobDone := make(chan bool) executionTimes := make([]int64, 0) numberOfIterations := 2 @@ -57,7 +56,7 @@ func testJobWithInterval(t *testing.T, sched *Scheduler, jb *job.Job, expectedTi } func TestSafeExecution(t *testing.T) { - sched := NewScheduler() + sched := New() success := false var wc sync.WaitGroup wc.Add(1) @@ -80,7 +79,7 @@ func TestSafeExecutionWithPanic(t *testing.T) { } }() - sched := NewScheduler() + sched := New() sched.Every(1).Second().DoJobSafely(func() { log.Panic("I am panicking!") }) @@ -88,7 +87,7 @@ func TestSafeExecutionWithPanic(t *testing.T) { } func TestScheduled(t *testing.T) { - n := NewScheduler() + n := New() n.Every(1).Second().Do(task) if !n.Scheduled(task) { t.Fatal("Task was scheduled but function couldn't find it") @@ -96,7 +95,7 @@ func TestScheduled(t *testing.T) { } func TestScheduler_Weekdays(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() job1 := scheduler.Every(1).Monday().At("23:59") job2 := scheduler.Every(1).Wednesday().At("23:59") @@ -108,7 +107,7 @@ func TestScheduler_Weekdays(t *testing.T) { } func TestScheduler_WeekdaysTodayAfter(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() now := time.Now() timeToSchedule := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()-1, 0, 0, time.Local) @@ -126,7 +125,7 @@ func TestScheduler_WeekdaysTodayAfter(t *testing.T) { } func TestScheduler_JobLocsSetProperly(t *testing.T) { - defaultScheduledJob := job.NewJob(10) + defaultScheduledJob := NewJob(10) assert.Equal(t, defaultScheduledJob.TimeLocation, time.Local) defaultScheduledJobFromScheduler := Every(10) assert.Equal(t, defaultScheduledJobFromScheduler.TimeLocation, time.Local) @@ -137,7 +136,7 @@ func TestScheduler_JobLocsSetProperly(t *testing.T) { } ChangeTimeLocation(laLocation) - modifiedGlobalLocJob := job.NewJob(10) + modifiedGlobalLocJob := NewJob(10) assert.Equal(t, modifiedGlobalLocJob.TimeLocation, laLocation) modifiedGlobalLocJobFromScheduler := Every(10) assert.Equal(t, modifiedGlobalLocJobFromScheduler.TimeLocation, laLocation) @@ -147,7 +146,7 @@ func TestScheduler_JobLocsSetProperly(t *testing.T) { t.Fatalf("unable to load America/Chicago time location") } - scheduler := NewScheduler() + scheduler := New() scheduler.ChangeLocation(chiLocation) modifiedGlobalLocJobFromScheduler = scheduler.Every(10) assert.Equal(t, modifiedGlobalLocJobFromScheduler.TimeLocation, chiLocation) @@ -162,7 +161,7 @@ func TestScheduleNextRunLoc(t *testing.T) { t.Fatalf("unable to load America/Los_Angeles time location") } - sched := NewScheduler() + sched := New() sched.ChangeLocation(time.UTC) job := sched.Every(1).Day().At("20:44") @@ -181,7 +180,7 @@ func TestScheduleNextRunLoc(t *testing.T) { func TestScheduleNextRunFromNow(t *testing.T) { now := time.Now() - sched := NewScheduler() + sched := New() sched.ChangeLocation(time.UTC) job := sched.Every(1).Hour().From(helper.NextTick()) @@ -198,7 +197,7 @@ func TestScheduleNextRunFromNow(t *testing.T) { // This is to ensure that if you schedule a job for today's weekday, and the time hasn't yet passed, the next run time // will be scheduled for today. func TestScheduler_WeekdaysTodayBefore(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() now := time.Now() timeToSchedule := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()+1, 0, 0, time.Local) @@ -297,7 +296,7 @@ func Test_formatTime(t *testing.T) { } // utility function for testing the weekday functions *on* the current weekday. -func callTodaysWeekday(job *job.Job) *job.Job { +func callTodaysWeekday(job *Job) *Job { switch time.Now().Weekday() { case 0: job.Sunday() @@ -318,7 +317,7 @@ func callTodaysWeekday(job *job.Job) *job.Job { } func TestScheduler_Remove(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() scheduler.Every(1).Minute().Do(task) scheduler.Every(1).Minute().Do(taskWithParams, 1, "hello") @@ -334,7 +333,7 @@ func TestScheduler_Remove(t *testing.T) { } func TestScheduler_RemoveByRef(t *testing.T) { - scheduler := NewScheduler() + scheduler := New() job1 := scheduler.Every(1).Minute() job1.Do(task) job2 := scheduler.Every(1).Minute() @@ -343,12 +342,12 @@ func TestScheduler_RemoveByRef(t *testing.T) { assert.Equal(t, 2, scheduler.Len(), "Incorrect number of jobs") scheduler.RemoveByRef(job1) - assert.ElementsMatch(t, []*job.Job{job2}, scheduler.Jobs()) + assert.ElementsMatch(t, []*Job{job2}, scheduler.Jobs()) } func TestTaskAt(t *testing.T) { // Create new scheduler to have clean test env - s := NewScheduler() + s := New() // Schedule to run in next minute now := time.Now() @@ -362,7 +361,7 @@ func TestTaskAt(t *testing.T) { }) // Expected start time - expectedStartTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Add(time.Minute).Minute(), 0, 0, global.TimeZone) + expectedStartTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Add(time.Minute).Minute(), 0, 0, types.TimeZone) nextRun := dayJob.NextScheduledTime() assert.Equal(t, expectedStartTime, nextRun) @@ -379,7 +378,7 @@ func TestTaskAt(t *testing.T) { func TestTaskAtFuture(t *testing.T) { // Create new scheduler to have clean test env - s := NewScheduler() + s := New() now := time.Now() @@ -394,7 +393,7 @@ func TestTaskAtFuture(t *testing.T) { }) // Check first run - expectedStartTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Add(time.Minute).Minute(), 0, 0, global.TimeZone) + expectedStartTime := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Add(time.Minute).Minute(), 0, 0, types.TimeZone) nextRun := dayJob.NextScheduledTime() assert.Equal(t, expectedStartTime, nextRun) @@ -410,28 +409,28 @@ func TestDaily(t *testing.T) { now := time.Now() // Create new scheduler to have clean test env - s := NewScheduler() + s := New() // schedule next run 1 day dayJob := s.Every(1).Day() dayJob.NextJobRun() tomorrow := now.AddDate(0, 0, 1) - expectedTime := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 0, 0, 0, 0, global.TimeZone) + expectedTime := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 0, 0, 0, 0, types.TimeZone) assert.Equal(t, expectedTime, dayJob.NextRun) // schedule next run 2 days dayJob = s.Every(2).Days() dayJob.NextJobRun() twoDaysFromNow := now.AddDate(0, 0, 2) - expectedTime = time.Date(twoDaysFromNow.Year(), twoDaysFromNow.Month(), twoDaysFromNow.Day(), 0, 0, 0, 0, global.TimeZone) + expectedTime = time.Date(twoDaysFromNow.Year(), twoDaysFromNow.Month(), twoDaysFromNow.Day(), 0, 0, 0, 0, types.TimeZone) assert.Equal(t, expectedTime, dayJob.NextRun) // Job running longer than next schedule 1day 2 hours dayJob = s.Every(1).Day() twoHoursFromNow := now.Add(2 * time.Hour) - dayJob.LastRun = time.Date(twoHoursFromNow.Year(), twoHoursFromNow.Month(), twoHoursFromNow.Day(), twoHoursFromNow.Hour(), 0, 0, 0, global.TimeZone) + dayJob.LastRun = time.Date(twoHoursFromNow.Year(), twoHoursFromNow.Month(), twoHoursFromNow.Day(), twoHoursFromNow.Hour(), 0, 0, 0, types.TimeZone) dayJob.NextJobRun() - expectedTime = time.Date(twoHoursFromNow.Year(), twoHoursFromNow.Month(), twoHoursFromNow.AddDate(0, 0, 1).Day(), 0, 0, 0, 0, global.TimeZone) + expectedTime = time.Date(twoHoursFromNow.Year(), twoHoursFromNow.Month(), twoHoursFromNow.AddDate(0, 0, 1).Day(), 0, 0, 0, 0, types.TimeZone) assert.Equal(t, expectedTime, dayJob.NextRun) // At() 2 hours before now @@ -442,7 +441,7 @@ func TestDaily(t *testing.T) { expectedTime = time.Date(twoHoursBefore.Year(), twoHoursBefore.Month(), twoHoursBefore.AddDate(0, 0, 1).Day(), - twoHoursBefore.Hour(), twoHoursBefore.Minute(), 0, 0, global.TimeZone) + twoHoursBefore.Hour(), twoHoursBefore.Minute(), 0, 0, types.TimeZone) assert.Equal(t, expectedTime, dayJob.NextRun) } @@ -451,10 +450,10 @@ func TestWeekdayAfterToday(t *testing.T) { now := time.Now() // Create new scheduler to have clean test env - s := NewScheduler() + s := New() // Schedule job at next week day - var weekJob *job.Job + var weekJob *Job switch now.Weekday() { case time.Monday: weekJob = s.Every(1).Tuesday() @@ -474,14 +473,14 @@ func TestWeekdayAfterToday(t *testing.T) { // First run weekJob.NextJobRun() - exp := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, global.TimeZone) + exp := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) // Simulate job run 7 days before weekJob.LastRun = weekJob.NextRun.AddDate(0, 0, -7) // Next run weekJob.NextJobRun() - exp = time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, global.TimeZone) + exp = time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) } @@ -489,10 +488,10 @@ func TestWeekdayBeforeToday(t *testing.T) { now := time.Now() // Create new scheduler to have clean test env - s := NewScheduler() + s := New() // Schedule job at day before - var weekJob *job.Job + var weekJob *Job switch now.Weekday() { case time.Monday: weekJob = s.Every(1).Sunday() @@ -513,14 +512,14 @@ func TestWeekdayBeforeToday(t *testing.T) { weekJob.NextJobRun() sixDaysFromNow := now.AddDate(0, 0, 6) - exp := time.Date(sixDaysFromNow.Year(), sixDaysFromNow.Month(), sixDaysFromNow.Day(), 0, 0, 0, 0, global.TimeZone) + exp := time.Date(sixDaysFromNow.Year(), sixDaysFromNow.Month(), sixDaysFromNow.Day(), 0, 0, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) // Simulate job run 7 days before weekJob.LastRun = weekJob.NextRun.AddDate(0, 0, -7) // Next run weekJob.NextJobRun() - exp = time.Date(sixDaysFromNow.Year(), sixDaysFromNow.Month(), sixDaysFromNow.Day(), 0, 0, 0, 0, global.TimeZone) + exp = time.Date(sixDaysFromNow.Year(), sixDaysFromNow.Month(), sixDaysFromNow.Day(), 0, 0, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) } @@ -532,10 +531,10 @@ func TestWeekdayAt(t *testing.T) { startAt := fmt.Sprintf("%02d:%02d", hour, minute) // Create new scheduler to have clean test env - s := NewScheduler() + s := New() // Schedule job at next week day - var weekJob *job.Job + var weekJob *Job switch now.Weekday() { case time.Monday: weekJob = s.Every(1).Tuesday().At(startAt) @@ -555,14 +554,14 @@ func TestWeekdayAt(t *testing.T) { // First run weekJob.NextJobRun() - exp := time.Date(now.Year(), now.Month(), now.AddDate(0, 0, 1).Day(), hour, minute, 0, 0, global.TimeZone) + exp := time.Date(now.Year(), now.Month(), now.AddDate(0, 0, 1).Day(), hour, minute, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) // Simulate job run 7 days before weekJob.LastRun = weekJob.NextRun.AddDate(0, 0, -7) // Next run weekJob.NextJobRun() - exp = time.Date(now.Year(), now.Month(), now.AddDate(0, 0, 1).Day(), hour, minute, 0, 0, global.TimeZone) + exp = time.Date(now.Year(), now.Month(), now.AddDate(0, 0, 1).Day(), hour, minute, 0, 0, types.TimeZone) assert.Equal(t, exp, weekJob.NextRun) } @@ -589,14 +588,14 @@ func (l *lockerMock) Unlock(key string) error { } func TestSetLocker(t *testing.T) { - if job.JobLocker != nil { + if jobLocker != nil { t.Fail() t.Log("Expected locker to not be set by default") } SetLocker(&lockerMock{}) - if job.JobLocker == nil { + if jobLocker == nil { t.Fail() t.Log("Expected locker to be set") } @@ -632,13 +631,13 @@ func TestLocker(t *testing.T) { }) for i := 0; i < 5; i++ { - s1 := NewScheduler() + s1 := New() s1.Every(1).Seconds().Lock().Do(task, "A", i) - s2 := NewScheduler() + s2 := New() s2.Every(1).Seconds().Lock().Do(task, "B", i) - s3 := NewScheduler() + s3 := New() s3.Every(1).Seconds().Lock().Do(task, "C", i) stop1 := s1.Start() @@ -666,7 +665,7 @@ func TestLocker(t *testing.T) { } func TestGetAllJobs(t *testing.T) { - defaultScheduler = NewScheduler() + defaultScheduler = New() Every(1).Minute().Do(task) Every(2).Minutes().Do(task) Every(3).Minutes().Do(task) diff --git a/global/global.go b/types/types.go similarity index 93% rename from global/global.go rename to types/types.go index 6504c40..727c6ea 100644 --- a/global/global.go +++ b/types/types.go @@ -1,4 +1,4 @@ -package global +package types import "time" diff --git a/job/units.go b/units.go similarity index 89% rename from job/units.go rename to units.go index f8e7672..fd50e26 100644 --- a/job/units.go +++ b/units.go @@ -1,38 +1,38 @@ -package job +package scheduler import ( - "github.com/Ja7ad/Scheduler/global" + "github.com/Ja7ad/scheduler/types" "time" ) // Seconds set the unit with seconds func (j *Job) Seconds() *Job { - return j.SetJobUnit(global.Seconds) + return j.SetJobUnit(types.Seconds) } // Minutes set the unit with minutes func (j *Job) Minutes() *Job { - return j.SetJobUnit(global.Minutes) + return j.SetJobUnit(types.Minutes) } // Hours set the unit with hours func (j *Job) Hours() *Job { - return j.SetJobUnit(global.Hours) + return j.SetJobUnit(types.Hours) } // Days set the unit with days func (j *Job) Days() *Job { - return j.SetJobUnit(global.Days) + return j.SetJobUnit(types.Days) } // Weeks set the unit with weeks func (j *Job) Weeks() *Job { - return j.SetJobUnit(global.Weeks) + return j.SetJobUnit(types.Weeks) } // Months set the unit with months func (j *Job) Months() *Job { - return j.SetJobUnit(global.Months) + return j.SetJobUnit(types.Months) } // Second sets the unit with second