github.com/astaxie/beego@v1.12.3/toolbox/task_test.go (about) 1 // Copyright 2014 beego Author. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package toolbox 16 17 import ( 18 "fmt" 19 "sync" 20 "testing" 21 "time" 22 ) 23 24 func TestParse(t *testing.T) { 25 tk := NewTask("taska", "0/30 * * * * *", func() error { fmt.Println("hello world"); return nil }) 26 err := tk.Run() 27 if err != nil { 28 t.Fatal(err) 29 } 30 AddTask("taska", tk) 31 StartTask() 32 time.Sleep(6 * time.Second) 33 StopTask() 34 } 35 36 func TestSpec(t *testing.T) { 37 wg := &sync.WaitGroup{} 38 wg.Add(2) 39 tk1 := NewTask("tk1", "0 12 * * * *", func() error { fmt.Println("tk1"); return nil }) 40 tk2 := NewTask("tk2", "0,10,20 * * * * *", func() error { fmt.Println("tk2"); wg.Done(); return nil }) 41 tk3 := NewTask("tk3", "0 10 * * * *", func() error { fmt.Println("tk3"); wg.Done(); return nil }) 42 43 AddTask("tk1", tk1) 44 AddTask("tk2", tk2) 45 AddTask("tk3", tk3) 46 StartTask() 47 defer StopTask() 48 49 select { 50 case <-time.After(200 * time.Second): 51 t.FailNow() 52 case <-wait(wg): 53 } 54 } 55 56 func wait(wg *sync.WaitGroup) chan bool { 57 ch := make(chan bool) 58 go func() { 59 wg.Wait() 60 ch <- true 61 }() 62 return ch 63 }