本文整理匯總了Golang中github.com/gorhill/cronexpr.Parse函數的典型用法代碼示例。如果您正苦於以下問題:Golang Parse函數的具體用法?Golang Parse怎麽用?Golang Parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Parse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: start
func (r Run) start(id int) {
for {
cexpr, err := cronexpr.Parse(r.Cron)
if err != nil {
panic(err)
}
// sleep until the next run is scheduled to happen
nrun := cexpr.Next(time.Now())
waitduration := nrun.Sub(time.Now())
log.Printf("[info] run %d will start at %v (in %v)", id, nrun, waitduration)
time.Sleep(waitduration)
notifchan := make(chan Notification)
done := make(chan bool)
go processNotifications(notifchan, done)
var wg sync.WaitGroup
for _, target := range r.Targets {
log.Printf("[info] run %d starting scan of target %q", id, target)
id, err := r.scan(target)
debugprint("got scan id %d", id)
if err != nil {
log.Printf("[error] failed to launch against %q: %v", target, err)
continue
}
wg.Add(1)
go r.evaluate(id, notifchan, &wg)
}
wg.Wait()
close(notifchan)
<-done
}
}
示例2: start
// Start a scheduler entity. This is normally run in it's own go-routine
// and will wait until the configured time to execute.
func (e *entity) start() {
xr := func(s string, args ...interface{}) {
mlog(s, args...)
e.deadChan <- true
}
e.abortRun = make(chan bool, 1)
for {
cexpr, err := cronexpr.Parse(e.cfg.Configuration.Schedule)
if err != nil {
xr("%v: bad cron expression: %v", e.name, err)
return
}
nrun := cexpr.Next(time.Now())
waitduration := nrun.Sub(time.Now())
mlog("%v: will run at %v (in %v)", e.name, nrun, waitduration)
select {
case <-e.abortRun:
mlog("%v: asked to terminate, stopping", e.name)
return
case <-time.After(waitduration):
}
mlog("%v: running", e.name)
err = e.launchAction()
if err != nil {
xr("%v: %v", e.name, err)
return
}
}
mlog("%v: job exiting", e.name)
e.deadChan <- true
}
示例3: getVersions
func getVersions(request models.CheckRequest) (models.CheckResponse, error) {
expr, err := cronexpr.Parse(request.Source.Expression)
if err != nil {
return nil, err
}
versions := []models.Version{}
shouldFire := false
loc, err := time.LoadLocation(request.Source.Location)
if err != nil {
return nil, err
}
previouslyFiredAt := request.Version.Time
if previouslyFiredAt.IsZero() {
previouslyFiredAt = time.Now().In(loc).Add(-1 * time.Hour)
}
shouldFireAt := expr.Next(previouslyFiredAt)
if previouslyFiredAt.Before(shouldFireAt) && time.Now().After(shouldFireAt) {
shouldFire = true
}
if shouldFire {
versions = append(versions, models.Version{
Time: time.Now().In(loc),
})
}
return versions, nil
}
示例4: Parse
// Parse returns a new Ticker containing a channel that will send the time
// with a period specified by the spec argument. Stop the ticker to release
// associated resources.
func Parse(spec string) (*Ticker, error) {
expr, err := cronexpr.Parse(spec)
if err != nil {
return nil, err
}
tickerC := make(chan time.Time, 1)
ticker := &Ticker{
C: tickerC,
done: make(chan struct{}, 1),
expr: expr,
}
go func() {
for {
next := ticker.expr.Next(c.Now())
select {
case <-time.After(next.Sub(c.Now())):
tickerC <- c.Now()
case <-ticker.done:
break
}
}
}()
return ticker, nil
}
示例5: NewConfig
// NewConfig parses the relevant environment variables, applying defaults if unspecified.
func NewConfig() (Config, error) {
c := Config{}
c.ErrInfo = os.Getenv("ERR_INFO") == "true"
ibGw := os.Getenv("IB_GW")
if ibGw == "" {
ibGw = "127.0.0.1:4002"
}
c.IbGws = strings.Split(ibGw, ",")
ibClientId := os.Getenv("IB_CID")
if ibClientId == "" {
ibClientId = "5555"
}
var err error
c.IbClientId, err = strconv.Atoi(ibClientId)
if err != nil {
return c, fmt.Errorf("IB_CID '%s' not an integer")
}
c.DbUrl = os.Getenv("DB_URL")
if c.DbUrl == "" {
c.DbUrl = "postgres://[email protected]/ibc_dev?sslmode=disable"
}
if !strings.HasPrefix(c.DbUrl, "postgres://") {
return c, fmt.Errorf("DB_URL '%s' did not being with postgres://", c.DbUrl)
}
portString := os.Getenv("PORT")
if portString == "" {
portString = "3000"
}
c.Port, err = strconv.Atoi(portString)
if err != nil {
return c, fmt.Errorf("PORT '%s' not an integer")
}
c.Host = os.Getenv("HOST")
if c.Host == "" {
c.Host = "localhost"
}
acctRefresh := os.Getenv("ACCT_REF")
if acctRefresh == "" {
acctRefresh = "@hourly"
}
c.AccountRefresh, err = cronexpr.Parse(acctRefresh)
if err != nil {
return c, err
}
return c, nil
}
示例6: New
// New returns a new cron expression.
// We use github.com/gorhill/cronexpr for parsing cron express inside.
func New(expr string) (schedule.Expression, error) {
cronexpr, err := cronexpr.Parse(expr)
if err != nil {
return nil, err
}
return &expression{
Expression: cronexpr,
}, nil
}
示例7: validate
func (e *entityConfig) validate() error {
if e.Configuration.Schedule == "" {
return fmt.Errorf("missing schedule")
}
_, err := cronexpr.Parse(e.Configuration.Schedule)
if err != nil {
return fmt.Errorf("bad cron expression: %v", err)
}
return nil
}
示例8: IsTimeToNotifyValid
func (c *Channel) IsTimeToNotifyValid() bool {
if c.TimeToNotify == ChannelSendImmediately {
return true
}
_, err := cronexpr.Parse(c.TimeToNotify)
if err != nil {
logger.WithField("time_to_notify", c.TimeToNotify).Warn("failed to parse time to notify")
}
return err == nil
}
示例9: newCronTicker
func newCronTicker(cronExpr string) (*cronTicker, error) {
expr, err := cronexpr.Parse(cronExpr)
if err != nil {
return nil, err
}
return &cronTicker{
expr: expr,
ticker: make(chan time.Time),
closing: make(chan struct{}),
}, nil
}
示例10: TestExpressions
func TestExpressions(t *testing.T) {
for _, test := range crontests {
for _, times := range test.times {
from, _ := time.Parse("2006-01-02 15:04:05", times.from)
expr, err := cronexpr.Parse(test.expr)
if err != nil {
t.Errorf(`cronexpr.Parse("%s") returned "%s"`, test.expr, err.Error())
}
next := expr.Next(from)
nextstr := next.Format(test.layout)
if nextstr != times.next {
t.Errorf(`("%s").Next("%s") = "%s", got "%s"`, test.expr, times.from, times.next, nextstr)
}
}
}
}
示例11: ShouldRun
func (e *Emissary) ShouldRun(t time.Time) (bool, error) {
t = t.Truncate(time.Minute)
compare := t.Add(-1 * time.Nanosecond)
for _, s := range e.Schedules {
parsed, err := cronexpr.Parse(s)
if err != nil {
return false, err
}
next := parsed.Next(compare)
if next == t {
return true, nil
}
}
return false, nil
}
示例12: Init
// Init initializes some internal data inside the Alert, and must be called
// after the Alert is unmarshaled from yaml (or otherwise created)
func (a *Alert) Init() error {
var err error
a.searchIndexTPL, err = templatizeHelper(a.SearchIndex, err)
a.searchTypeTPL, err = templatizeHelper(a.SearchType, err)
a.searchTPL, err = templatizeHelper(&a.Search, err)
if err != nil {
return err
}
cron, err := cronexpr.Parse(a.Interval)
if err != nil {
return fmt.Errorf("parsing interval: %s", err)
}
a.cron = cron
return nil
}
示例13: main
func main() {
var err error
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "%s - Manage users in various SaaS based on a LDAP source\n"+
"Usage: %s -c config.yaml\n",
os.Args[0], os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if *showVersion {
fmt.Println(version)
os.Exit(0)
}
// load the local configuration file
conf, err := loadConf(*config)
if err != nil {
log.Fatalf("failed to load configuration: %v", err)
}
// just run once
if *once || conf.Cron == "disabled" {
run(conf)
return
}
// infinite loop, wake up at the cron period
for {
cexpr, err := cronexpr.Parse(conf.Cron)
if err != nil {
log.Fatalf("failed to parse cron string %q: %v", conf.Cron, err)
}
// sleep until the next run is scheduled to happen
nrun := cexpr.Next(time.Now())
waitduration := nrun.Sub(time.Now())
log.Printf("[info] next run will start at %v (in %v)", nrun, waitduration)
time.Sleep(waitduration)
run(conf)
}
}
示例14: NeedAutoStart
// goroutine run this function periodly to check if this job is needed to auto start
func (j Job) NeedAutoStart() bool {
if len(j.Schedule) > 0 {
expr, err := cronexpr.Parse(j.Schedule)
if err != nil {
log.Debug(err.Error())
return false
}
last_run_ts := j.GetLastRunTime()
if last_run_ts >= 0 {
last_run_time := time.Unix(last_run_ts, 0)
next_time := expr.Next(last_run_time)
log.Debug("next_time", next_time)
// > 20s
if time.Now().Unix()-next_time.Unix() > 20 {
return true
}
}
}
return false
}
示例15: NewTaskRouteHandler
// NewTaskRouteHandler creates a new task with the POST'd data
func NewTaskRouteHandler(ren *render.Render, dispatcher *dispatcher.Dispatcher) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var nt database.Task
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&nt)
if err != nil {
ren.JSON(w, 400, map[string]error{"error": err})
return
}
defer r.Body.Close()
switch {
case nt.Name == "":
ren.JSON(w, 400, map[string]error{"error": ErrMissingNameField})
return
case nt.CMD == "":
ren.JSON(w, 400, map[string]error{"error": ErrMissingCMDField})
return
case nt.Args == "":
ren.JSON(w, 400, map[string]error{"error": ErrMissingArgsField})
return
case nt.Schedule == "":
ren.JSON(w, 400, map[string]error{"error": ErrMissingScheduleField})
return
}
// validate that the entered cron string is valid. Error if not.
_, err = cronexpr.Parse(nt.Schedule)
if err != nil {
ren.JSON(w, 400, map[string]error{"error": err})
return
}
dispatcher.SenderChan <- &nt
dispatcher.TaskProcChan <- nt
ren.JSON(w, http.StatusOK, map[string]database.Task{"task": nt})
}
}