2015-12-24 153 views
1

我使用cron中PKG https://github.com/jasonlvhit/gocron/blob/master/gocron.gocron作业中GOLANG

import (
    "fmt" 
    "time" 

    "github.com/claudiu/gocron" 
) 

func task() { 
    fmt.Println("I am runnning task.", time.Now()) 
} 
func vijay() { 
    fmt.Println("I am runnning vijay.", time.Now()) 
} 

func main() { 
    go test() 

    gocron.Start() 
    s := gocron.NewScheduler() 
    gocron.Every(5).Seconds().Do(task) 
    gocron.Every(10).Seconds().Do(vijay) 

    <-s.Start() 

} 
func test() { 
    time.Sleep(20 * time.Second) 
    gocron.Clear() 
    fmt.Println("All task removed") 
} 

我的问题是删除所有作业后,我的程序仍在删除所有作业后执行

我想打破exection

请帮我看看,我无法找出如何去做, 我试图改变PKG的源代码,但也没能找到办法做到这一点

谢谢大家

+0

这只是礼貌让人们不要浪费自己的时间您的跨岗位之间的链接:https://groups.google.com/forum/?fromgroups#!topic/golang -nuts/yayvQLhR4Bk – JimB

+0

我很抱歉,先生,我会牢记这一点 – GKV

回答

4

首先,您正在创建一个新的调度程序,并等待它,但使用默认调度程序来运行您的作业。

接下来,您阻止了Start()方法返回的频道。关闭该通道以解除接收操作。如果您没有立即从main退出,这也将退出cron程序的主循环。

func main() { 
    ch := gocron.Start() 
    go test(ch) 
    gocron.Every(5).Seconds().Do(task) 
    gocron.Every(10).Seconds().Do(vijay) 

    <-ch 
} 
func test(stop chan bool) { 
    time.Sleep(20 * time.Second) 
    gocron.Clear() 
    fmt.Println("All task removed") 
    close(stop) 
} 

这实际上是一样的

func main() { 
    gocron.Start() 
    gocron.Every(5).Seconds().Do(task) 
    gocron.Every(10).Seconds().Do(vijay) 

    time.Sleep(20 * time.Second) 

    gocron.Clear() 
    fmt.Println("All task removed") 
} 

如果你马上离开,这并不重要,如果你叫Clear()先停止调度程序,你可以简单地退出程序。

2

JimB rights。但我不知道你为什么使用gocron方法和s方法。这个例子正常工作:

package main 

import (
    "fmt" 
    "time" 

    "github.com/claudiu/gocron" 
) 

func task() { 
    fmt.Println("I am runnning task.", time.Now()) 
} 
func vijay() { 
    fmt.Println("I am runnning vijay.", time.Now()) 
} 

func main() { 
    s := gocron.NewScheduler() 
    s.Every(2).Seconds().Do(task) 
    s.Every(4).Seconds().Do(vijay) 

    sc := s.Start() // keep the channel 
    go test(s, sc) // wait 
    <-sc   // it will happens if the channel is closed 
} 
func test(s *gocron.Scheduler, sc chan bool) { 
    time.Sleep(8 * time.Second) 
    s.Clear() 
    fmt.Println("All task removed") 
    close(sc) // close the channel 
}