当前位置: 首页>>代码示例>>Golang>>正文


Golang cronexpr.Parse函数代码示例

本文整理汇总了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
	}
}
开发者ID:mozilla,项目名称:tls-observatory,代码行数:32,代码来源:main.go

示例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
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:34,代码来源:entity.go

示例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
}
开发者ID:pivotal-cf-experimental,项目名称:cron-resource,代码行数:34,代码来源:check.go

示例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
}
开发者ID:f2prateek,项目名称:cron,代码行数:30,代码来源:cron.go

示例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
}
开发者ID:jacktang,项目名称:ibconnect.go,代码行数:57,代码来源:config.go

示例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
}
开发者ID:wayn3h0,项目名称:go-schedule,代码行数:12,代码来源:cron.go

示例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
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:10,代码来源:entity.go

示例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
}
开发者ID:shuhaowu,项目名称:towncrier,代码行数:11,代码来源:config.go

示例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
}
开发者ID:yuanwr,项目名称:kapacitor,代码行数:11,代码来源:batch.go

示例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)
			}
		}
	}
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:16,代码来源:cronexpr_test.go

示例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
}
开发者ID:CarlosUh,项目名称:emissary,代码行数:16,代码来源:emissary.go

示例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
}
开发者ID:thebennos,项目名称:thumper-1,代码行数:19,代码来源:alert.go

示例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)
	}
}
开发者ID:mozilla-services,项目名称:userplex,代码行数:42,代码来源:main.go

示例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
}
开发者ID:jackwanger,项目名称:tyrant,代码行数:21,代码来源:job.go

示例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})
	}
}
开发者ID:srhopkins,项目名称:aion,代码行数:40,代码来源:tasks.go


注:本文中的github.com/gorhill/cronexpr.Parse函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。