Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update all exported comments and start example_test.go for godoc #15

Merged
merged 4 commits into from
Mar 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gocron_test

import (
"fmt"
"time"

"github.com/go-co-op/gocron"
)

func ExampleScheduler_Start() {
s := gocron.NewScheduler(time.UTC)
s.Every(3).Seconds().Do(func() { fmt.Println("I am a task") })
<-s.Start()
}

func ExampleScheduler_At() {
s := gocron.NewScheduler(time.UTC)
s.Every(1).Day().At("10:30").Do(func() { fmt.Println("I am a task") })
s.Every(1).Monday().At("10:30:01").Do(func() { fmt.Println("I am a task") })
}

func ExampleJob_GetScheduledTime() {
s := gocron.NewScheduler(time.UTC)
job, _ := s.Every(1).Day().At("10:30").Do(func() { fmt.Println("I am a task") })
fmt.Println(job.GetScheduledTime())
// Output: 10:30
}
28 changes: 15 additions & 13 deletions gocron.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,6 @@
// for configuration. Schedule lets you run Golang functions periodically
// at pre-determined intervals using a simple, human-friendly syntax.
//
// Inspired by the Ruby module clockwork <https://github.com/tomykaira/clockwork>
// and
// Python package schedule <https://github.com/dbader/schedule>
//
// See also
// http://adam.heroku.com/past/2010/4/13/rethinking_cron/
// http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/
//
// Copyright 2014 Jason Lyu. jasonlvhit@gmail.com .
// All rights reserved.
// Use of this source code is governed by a BSD-style .
Expand All @@ -20,16 +12,26 @@ package gocron

import (
"crypto/sha256"
"errors"
"fmt"
"reflect"
"runtime"
"strconv"
"strings"
)

// Locker provides a method to lock jobs from running
// at the same time on multiple instances of gocron.
// You can provide any locker implementation you wish.
// Error declarations for gocron related errors
var (
JohnRoesler marked this conversation as resolved.
Show resolved Hide resolved
ErrTimeFormat = errors.New("time format error")
ErrParamsNotAdapted = errors.New("the number of params is not adapted")
ErrNotAFunction = errors.New("only functions can be schedule into the job queue")
ErrPeriodNotSpecified = errors.New("unspecified job period")
ErrNotScheduledWeekday = errors.New("job not scheduled weekly on a weekday")
)

// Locker provides an interface for implementing job locking
// to prevent jobs from running at the same time on multiple
// instances of gocron
type Locker interface {
Lock(key string) (bool, error)
Unlock(key string) error
Expand All @@ -49,7 +51,8 @@ var (
locker Locker
)

// SetLocker sets a locker implementation
// SetLocker sets a locker implementation to be used by
// the scheduler for locking jobs
func SetLocker(l Locker) {
locker = l
}
Expand All @@ -66,7 +69,6 @@ func callJobFuncWithParams(jobFunc interface{}, params []interface{}) ([]reflect
return f.Call(in), nil
}

// for given function fn, get the name of function.
func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
}
Expand Down
59 changes: 29 additions & 30 deletions job.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
package gocron

import (
"errors"
"fmt"
"time"
)

// Error declarations for gocron
var (
ErrTimeFormat = errors.New("time format error")
ErrParamsNotAdapted = errors.New("the number of params is not adapted")
ErrNotAFunction = errors.New("only functions can be schedule into the job queue")
ErrPeriodNotSpecified = errors.New("unspecified job period")
ErrParameterCannotBeNil = errors.New("nil paramaters cannot be used with reflection")
)

// Job struct keeping information about job
// Job struct stores the information necessary to run a Job
type Job struct {
interval uint64 // pause interval * unit between runs
startsImmediately bool // if the job should run upon scheduler start
jobFunc string // the job jobFunc to run, func[jobFunc]
startsImmediately bool // if the Job should run upon scheduler start
jobFunc string // the Job jobFunc to run, func[jobFunc]
unit timeUnit // time units, ,e.g. 'minutes', 'hours'...
atTime time.Duration // optional time at which this job runs
err error // error related to job
atTime time.Duration // optional time at which this Job runs
err error // error related to Job
lastRun time.Time // datetime of last run
nextRun time.Time // datetime of next run
startDay time.Weekday // Specific day of the week to start on
funcs map[string]interface{} // Map for the function task store
fparams map[string][]interface{} // Map for function and params of function
lock bool // lock the job from running at same time form multiple instances
tags []string // allow the user to tag jobs with certain labels
lock bool // lock the Job from running at same time form multiple instances
tags []string // allow the user to tag Jobs with certain labels
time timeHelper // an instance of timeHelper to interact with the time package
}

// NewJob creates a new job with the time interval.
// NewJob creates a new Job with the provided interval
func NewJob(interval uint64) *Job {
th := newTimeHelper()
return &Job{
Expand All @@ -47,32 +38,32 @@ func NewJob(interval uint64) *Job {
}
}

// True if the job should be run now
// shouldRun returns true if the Job should be run now
func (j *Job) shouldRun() bool {
return j.time.Now().Unix() >= j.nextRun.Unix()
}

//Run the job and immediately reschedule it
// Run the Job and immediately reschedule it
func (j *Job) run() {
j.lastRun = j.time.Now()
go callJobFuncWithParams(j.funcs[j.jobFunc], j.fparams[j.jobFunc])
}

// Err should be checked to ensure an error didn't occur creating the job
// Err returns an error if one ocurred while creating the Job
func (j *Job) Err() error {
return j.err
}

// Tag allows you to add labels to a job
// they don't impact the functionality of the job.
// Tag allows you to add arbitrary labels to a Job that do not
// impact the functionality of the Job
func (j *Job) Tag(t string, others ...string) {
j.tags = append(j.tags, t)
for _, tag := range others {
j.tags = append(j.tags, tag)
}
}

// Untag removes a tag from a job
// Untag removes a tag from a Job
func (j *Job) Untag(t string) {
newTags := []string{}
for _, tag := range j.tags {
Expand All @@ -84,7 +75,7 @@ func (j *Job) Untag(t string) {
j.tags = newTags
}

// Tags returns the tags attached to the job
// Tags returns the tags attached to the Job
func (j *Job) Tags() []string {
return j.tags
}
Expand All @@ -110,13 +101,21 @@ func (j *Job) periodDuration() (time.Duration, error) {
return periodDuration, nil
}

// NextScheduledTime returns the time of when this job is to run next
// NextScheduledTime returns the time of the Job's next scheduled run
func (j *Job) NextScheduledTime() time.Time {
return j.nextRun
}

// GetWeekday returns which day of the week the job will run on
// This should only be used when .Weekday(...) was called on the job.
func (j *Job) GetWeekday() time.Weekday {
return j.startDay
// GetScheduledTime returns the specific time of day the Job will run at
func (j *Job) GetScheduledTime() string {
return fmt.Sprintf("%d:%d", j.atTime/time.Hour, (j.atTime%time.Hour)/time.Minute)
}

// GetWeekday returns which day of the week the Job will run on and
// will return an error if the Job is not scheduled weekly
func (j *Job) GetWeekday() (time.Weekday, error) {
if j.unit == weeks {
return j.startDay, nil
}
return time.Sunday, ErrNotScheduledWeekday
}
32 changes: 28 additions & 4 deletions job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,36 @@ func TestTags(t *testing.T) {
assert.ElementsMatch(t, j.Tags(), []string{"tags", "tag", "some"})
}

func TestGetAt(t *testing.T) {
func TestGetScheduledTime(t *testing.T) {
j, _ := NewScheduler(time.UTC).Every(1).Minute().At("10:30").Do(task)
assert.Equal(t, "10:30", j.GetAt())
assert.Equal(t, "10:30", j.GetScheduledTime())
}

func TestGetWeekday(t *testing.T) {
j, _ := NewScheduler(time.UTC).Every(1).Weekday(time.Wednesday).Do(task)
assert.Equal(t, time.Wednesday, j.GetWeekday())
s := NewScheduler(time.UTC)
weedayJob, _ := s.Every(1).Weekday(time.Wednesday).Do(task)
nonWeekdayJob, _ := s.Every(1).Minute().Do(task)

testCases := []struct {
desc string
job *Job
expectedWeekday time.Weekday
expectedError error
}{
{"success", weedayJob, time.Wednesday, nil},
{"fail - not set for weekday", nonWeekdayJob, time.Sunday, ErrNotScheduledWeekday},
}

for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
weekday, err := tc.job.GetWeekday()
if tc.expectedError != nil {
assert.Error(t, tc.expectedError, err)
} else {
assert.Nil(t, err)
}

assert.Equal(t, tc.expectedWeekday, weekday)
})
}
}
Loading