Browse Source

Make location non-modifiable, add test

Wannes 9 years ago
parent
commit
f6d519fc85
2 changed files with 37 additions and 4 deletions
  1. 9 4
      cron.go
  2. 28 0
      cron_test.go

+ 9 - 4
cron.go

@@ -72,6 +72,11 @@ func (s byTime) Less(i, j int) bool {
 
 // New returns a new Cron job runner.
 func New() *Cron {
+	return NewWithLocation(time.Now().Location())
+}
+
+// NewWithLocation returns a new Cron job runner.
+func NewWithLocation(location *time.Location) *Cron {
 	return &Cron{
 		entries:  nil,
 		add:      make(chan *Entry),
@@ -79,7 +84,7 @@ func New() *Cron {
 		snapshot: make(chan []*Entry),
 		running:  false,
 		ErrorLog: nil,
-		location: time.Now().Location(),
+		location: location,
 	}
 }
 
@@ -127,9 +132,9 @@ func (c *Cron) Entries() []*Entry {
 	return c.entrySnapshot()
 }
 
-// SetLocation sets the time zone location
-func (c *Cron) SetLocation(location *time.Location) {
-	c.location = location
+// Location gets the time zone location
+func (c *Cron) Location() *time.Location {
+	return c.location
 }
 
 // Start the cron scheduler in its own go-routine.

+ 28 - 0
cron_test.go

@@ -237,6 +237,34 @@ func TestLocalTimezone(t *testing.T) {
 	}
 }
 
+
+// Test that the cron is run in the given time zone (as opposed to local).
+func TestNonLocalTimezone(t *testing.T) {
+	wg := &sync.WaitGroup{}
+	wg.Add(1)
+
+	loc, err := time.LoadLocation("Atlantic/Cape_Verde")
+	if err != nil {
+		fmt.Printf("Failed to load time zone Atlantic/Cape_Verde: %+v", err)
+		t.Fail()
+	}
+
+	now := time.Now().In(loc)
+	spec := fmt.Sprintf("%d %d %d %d %d ?",
+		now.Second()+1, now.Minute(), now.Hour(), now.Day(), now.Month())
+
+	cron := NewWithLocation(loc)
+	cron.AddFunc(spec, func() { wg.Done() })
+	cron.Start()
+	defer cron.Stop()
+
+	select {
+	case <-time.After(ONE_SECOND):
+		t.FailNow()
+	case <-wait(wg):
+	}
+}
+
 // Test that calling stop before start silently returns without
 // blocking the stop channel.
 func TestStopWithoutStart(t *testing.T) {