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


Golang Time.Duration函数代码示例

本文整理汇总了Golang中Time.Duration函数的典型用法代码示例。如果您正苦于以下问题:Golang Duration函数的具体用法?Golang Duration怎么用?Golang Duration使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Duration函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: LSBaseQuery

// LSBaseQuery builds the base query that both LSCount and LSStat share
func LSBaseQuery(now time.Time, indexRoot string, l LogstashElasticHosts, keystring string, filter, sduration, eduration string, size int) (*LogstashRequest, error) {
	start, err := opentsdb.ParseDuration(sduration)
	if err != nil {
		return nil, err
	}
	var end opentsdb.Duration
	if eduration != "" {
		end, err = opentsdb.ParseDuration(eduration)
		if err != nil {
			return nil, err
		}
	}
	st := now.Add(time.Duration(-start))
	en := now.Add(time.Duration(-end))
	r := LogstashRequest{
		IndexRoot: indexRoot,
		Start:     &st,
		End:       &en,
		Source:    elastic.NewSearchSource().Size(size),
	}
	tf := elastic.NewRangeFilter("@timestamp").Gte(st).Lte(en)
	filtered := elastic.NewFilteredQuery(tf)
	r.KeyMatches, err = ProcessLSKeys(keystring, filter, &filtered)
	if err != nil {
		return nil, err
	}
	r.Source = r.Source.Query(filtered)
	return &r, nil
}
开发者ID:reduxdj,项目名称:grafana,代码行数:30,代码来源:logstash.go

示例2: domainDAOPerformanceReport

// Generates a report with the amount of time for each operation in the domain DAO. For
// more realistic values it does the same operation for the same amount of data X number
// of times to get the average time of the operation. After some results, with indexes we
// get 80% better performance, another good improvements was to create and remove many
// objects at once using go routines
func domainDAOPerformanceReport(reportFile string, domainDAO dao.DomainDAO) {
	// Report header
	report := " #       | Total            | Insert           | Find             | Remove\n" +
		"------------------------------------------------------------------------------------\n"

	// Report variables
	averageTurns := 5
	scale := []int{10, 50, 100, 500, 1000, 5000,
		10000, 50000, 100000, 500000, 1000000, 5000000}

	for _, numberOfItems := range scale {
		var totalDuration, insertDuration, queryDuration, removeDuration time.Duration

		for i := 0; i < averageTurns; i++ {
			utils.Println(fmt.Sprintf("Generating report - scale %d - turn %d", numberOfItems, i+1))
			totalDurationTmp, insertDurationTmp, queryDurationTmp, removeDurationTmp :=
				calculateDomainDAODurations(domainDAO, numberOfItems)

			totalDuration += totalDurationTmp
			insertDuration += insertDurationTmp
			queryDuration += queryDurationTmp
			removeDuration += removeDurationTmp
		}

		report += fmt.Sprintf("% -8d | % 16s | % 16s | % 16s | % 16s\n",
			numberOfItems,
			time.Duration(int64(totalDuration)/int64(averageTurns)).String(),
			time.Duration(int64(insertDuration)/int64(averageTurns)).String(),
			time.Duration(int64(queryDuration)/int64(averageTurns)).String(),
			time.Duration(int64(removeDuration)/int64(averageTurns)).String(),
		)
	}

	utils.WriteReport(reportFile, report)
}
开发者ID:rafaeljusto,项目名称:shelter,代码行数:40,代码来源:dao_domain.go

示例3: ParseTimeInterval

func ParseTimeInterval(source string) (time.Duration, error) {
	matches := intervalRegex.FindStringSubmatch(strings.ToLower(source))

	if matches == nil {
		return 0, errors.New("Invalid time interval " + source)
	}

	val, err := strconv.Atoi(matches[1])

	if err != nil {
		return 0, err
	}

	switch matches[2] {
	case "s":
		return time.Duration(val) * time.Second, nil

	case "m":
		return time.Duration(val) * time.Second * 60, nil

	case "h":
		return time.Duration(val) * time.Second * 60 * 60, nil

	case "d":
		return time.Duration(val) * time.Second * 60 * 60 * 24, nil

	case "w":
		return time.Duration(val) * time.Second * 60 * 60 * 24 * 7, nil

	default:
		return 0, errors.New("Invalid time interval " + source)
	}
}
开发者ID:nagyistge,项目名称:gotelemetry_agent,代码行数:33,代码来源:interval.go

示例4: setDefaults

// setDefaults sets default values for any Worker fields that are
// uninitialized.
func (w *Worker) setDefaults() {
	if w.WorkerID == "" {
		// May as well use a UUID here, "it's what we've always done"
		w.WorkerID = uuid.NewV4().String()
	}

	if w.Concurrency == 0 {
		w.Concurrency = runtime.NumCPU()
	}

	if w.PollInterval == time.Duration(0) {
		w.PollInterval = time.Duration(1) * time.Second
	}

	if w.HeartbeatInterval == time.Duration(0) {
		w.HeartbeatInterval = time.Duration(15) * time.Second
	}

	if w.MaxAttempts == 0 {
		w.MaxAttempts = 100
	}

	if w.Clock == nil {
		w.Clock = clock.New()
	}
}
开发者ID:diffeo,项目名称:go-coordinate,代码行数:28,代码来源:worker.go

示例5: Start

func (d *UDPClient) Start(uri *url.URL) error {
	d.url = uri
	d.stop = make(chan struct{})

	params := uri.Query()
	// The address must not have a port, as otherwise both announce and lookup
	// sockets would try to bind to the same port.
	addr, err := net.ResolveUDPAddr(d.url.Scheme, params.Get("listenaddress")+":0")
	if err != nil {
		return err
	}
	d.listenAddress = addr

	broadcastSeconds, err := strconv.ParseUint(params.Get("broadcast"), 0, 0)
	if err != nil {
		d.globalBroadcastInterval = DefaultGlobalBroadcastInterval
	} else {
		d.globalBroadcastInterval = time.Duration(broadcastSeconds) * time.Second
	}

	retrySeconds, err := strconv.ParseUint(params.Get("retry"), 0, 0)
	if err != nil {
		d.errorRetryInterval = DefaultErrorRetryInternval
	} else {
		d.errorRetryInterval = time.Duration(retrySeconds) * time.Second
	}

	d.wg.Add(1)
	go d.broadcast()
	return nil
}
开发者ID:KFDCompiled,项目名称:syncthing,代码行数:31,代码来源:client_udp.go

示例6: serve

// serve starts serving the provided http.Handler using security settings derived from the MasterConfig
func (c *MasterConfig) serve(handler http.Handler, extra []string) {
	timeout := c.Options.ServingInfo.RequestTimeoutSeconds
	if timeout == -1 {
		timeout = 0
	}

	server := &http.Server{
		Addr:           c.Options.ServingInfo.BindAddress,
		Handler:        handler,
		ReadTimeout:    time.Duration(timeout) * time.Second,
		WriteTimeout:   time.Duration(timeout) * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go util.Forever(func() {
		for _, s := range extra {
			glog.Infof(s, c.Options.ServingInfo.BindAddress)
		}
		if c.TLS {
			server.TLSConfig = &tls.Config{
				// Change default from SSLv3 to TLSv1.0 (because of POODLE vulnerability)
				MinVersion: tls.VersionTLS10,
				// Populate PeerCertificates in requests, but don't reject connections without certificates
				// This allows certificates to be validated by authenticators, while still allowing other auth types
				ClientAuth: tls.RequestClientCert,
				ClientCAs:  c.ClientCAs,
			}
			glog.Fatal(cmdutil.ListenAndServeTLS(server, c.Options.ServingInfo.BindNetwork, c.Options.ServingInfo.ServerCert.CertFile, c.Options.ServingInfo.ServerCert.KeyFile))
		} else {
			glog.Fatal(server.ListenAndServe())
		}
	}, 0)
}
开发者ID:ncantor,项目名称:origin,代码行数:34,代码来源:master.go

示例7: handleGraphiteTextProtocol

// Handles incoming requests for both TCP and UDP
func handleGraphiteTextProtocol(t *trTransceiver, conn net.Conn, timeout int) {

	defer conn.Close() // decrements tcpWg

	if timeout != 0 {
		conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
	}

	// We use the Scanner, becase it has a MaxScanTokenSize of 64K

	connbuf := bufio.NewScanner(conn)

	for connbuf.Scan() {
		packetStr := connbuf.Text()

		if dp, err := parseGraphitePacket(packetStr); err != nil {
			log.Printf("handleGraphiteTextProtocol(): bad backet: %v")
		} else {
			t.queueDataPoint(dp)
		}

		if timeout != 0 {
			conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
		}
	}

	if err := connbuf.Err(); err != nil {
		log.Println("handleGraphiteTextProtocol(): Error reading: %v", err)
	}
}
开发者ID:karlitxo,项目名称:tgres,代码行数:31,代码来源:services.go

示例8: run

// run periodically probes the container.
func (w *worker) run() {
	probeTickerPeriod := time.Duration(w.spec.PeriodSeconds) * time.Second
	probeTicker := time.NewTicker(probeTickerPeriod)

	defer func() {
		// Clean up.
		probeTicker.Stop()
		if !w.containerID.IsEmpty() {
			w.resultsManager.Remove(w.containerID)
		}

		w.probeManager.removeWorker(w.pod.UID, w.container.Name, w.probeType)
	}()

	// If kubelet restarted the probes could be started in rapid succession.
	// Let the worker wait for a random portion of tickerPeriod before probing.
	time.Sleep(time.Duration(rand.Float64() * float64(probeTickerPeriod)))

probeLoop:
	for w.doProbe() {
		// Wait for next probe tick.
		select {
		case <-w.stopCh:
			break probeLoop
		case <-probeTicker.C:
			// continue
		}
	}
}
开发者ID:leecalcote,项目名称:kubernetes,代码行数:30,代码来源:worker.go

示例9: sendata

func (r *gatewayB) sendata() {
	if r.flow.timeTxDone.After(Now) {
		return
	}
	for _, tioint := range r.tios {
		tio := tioint.(*TioOffset)
		tid := tio.GetID()
		if r.ack[tid] {
			continue
		}
		if tio.offset >= tio.totalbytes {
			continue
		}
		frsize := int64(configNetwork.sizeFrame)
		if tio.offset+frsize > tio.totalbytes {
			frsize = tio.totalbytes - tio.offset
		}
		newbits := frsize * 8
		if r.rb.below(newbits) {
			continue
		}
		assert(tio.GetTarget() == r.flow.to)
		ev := newRepDataEvent(r.realobject(), r.flow.to, tio, tio.offset, int(frsize))

		// transmit given the current flow's bandwidth
		d := time.Duration(newbits) * time.Second / time.Duration(r.flow.getbw())
		ok := r.Send(ev, SmethodWait)
		assert(ok)

		tio.offset += frsize
		r.flow.timeTxDone = Now.Add(d)
		r.rb.use(newbits)
		break
	}
}
开发者ID:hqr,项目名称:surge,代码行数:35,代码来源:mb.go

示例10: Check

func (t *Telnet) Check(srv Service) (bool, error) {
	t.deadline = time.Now().Add(time.Duration(time.Duration(srv.Timeout) * time.Second))

	c, err := net.DialTimeout("tcp", srv.URL, t.deadline.Sub(time.Now()))
	if err != nil {
		return false, err
	}

	_, err = t.recv(c)
	if err != nil {
		return false, err
	}

	if err := t.sendAYT(c); err != nil {
		return false, err
	}

	n, err := t.recv(c)
	if err != nil {
		return false, err
	}

	if n == 0 {
		return false, errors.New("no response to AYT")
	}

	return true, nil
}
开发者ID:dbulkow,项目名称:sitecheck,代码行数:28,代码来源:telnet.go

示例11: Call

// Converts the value to a duration in the given units
func (*duration) Call(args ...interface{}) (v interface{}, err error) {
	if len(args) != 1 && len(args) != 2 {
		return time.Duration(0), errors.New("duration expects one or two arguments duration(value, unit) where unit is optional depending on the type of value.")
	}

	getUnit := func() (time.Duration, error) {
		if len(args) != 2 {
			return 0, errors.New("duration expects unit argument for int and float values")
		}
		unit, ok := args[1].(time.Duration)
		if !ok {
			return 0, fmt.Errorf("invalid duration unit type: %T", args[1])
		}
		return unit, nil
	}
	var unit time.Duration
	switch a := args[0].(type) {
	case time.Duration:
		v = a
	case int64:
		unit, err = getUnit()
		v = time.Duration(a) * unit
	case float64:
		unit, err = getUnit()
		v = time.Duration(a * float64(unit))
	case string:
		v, err = influxql.ParseDuration(a)
		if err != nil {
			err = fmt.Errorf("invalid duration string %q", a)
		}
	default:
		err = fmt.Errorf("cannot convert %T to duration", a)
	}
	return
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:36,代码来源:functions.go

示例12: waitAndStop

func (p *Pool) waitAndStop() error {
	retryInterval := time.Duration(500)

	retriesLimit := int(time.Duration(60000) / retryInterval)
	retries := 0

	queueTicker := time.NewTicker(time.Millisecond * retryInterval)
	// Retry evenry 500ms to check if job queue is empty
	for _ = range queueTicker.C {
		// Check if jobQueue is empty and all workers are available
		if len(p.jobQueue) == 0 && len(p.workerPool) == p.maxWorkers {
			for _, worker := range p.workers {
				worker.Stop()
			}

			break
		}

		retries++
		if retries >= retriesLimit {
			queueTicker.Stop()

			return fmt.Errorf(fmt.Sprintf("checking queue status exceeded retry limit: %v", time.Duration(retries)*retryInterval*time.Millisecond))
		}
	}

	// Stop job queue ticker
	queueTicker.Stop()

	return nil
}
开发者ID:vladiacob,项目名称:go_workerpool,代码行数:31,代码来源:pool.go

示例13: startEnquireLink

func (t *Receiver) startEnquireLink(eli int) {
	t.eLTicker = time.NewTicker(time.Duration(eli) * time.Second)
	// check delay is half the time of enquire link intervel
	d := time.Duration(eli/2) * time.Second
	t.eLCheckTimer = time.NewTimer(d)
	t.eLCheckTimer.Stop()

	for {
		select {
		case <-t.eLTicker.C:

			p, _ := t.EnquireLink()
			if err := t.Write(p); err != nil {
				t.Err = SmppELWriteErr
				t.Close()
				return
			}

			t.eLCheckTimer.Reset(d)
		case <-t.eLCheckTimer.C:
			t.Err = SmppELRespErr
			t.Close()
			return
		}
	}
}
开发者ID:XmsCoders,项目名称:smpp34,代码行数:26,代码来源:receiver.go

示例14: parseTimeout

func parseTimeout(timeout ...float64) time.Duration {
	if len(timeout) == 0 {
		return time.Duration(defaultTimeout * int64(time.Second))
	} else {
		return time.Duration(timeout[0] * float64(time.Second))
	}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:7,代码来源:ginkgo_dsl.go

示例15: startTimer

func (rn *RaftNode) startTimer() {

	rn.debug_output2("timer started..", "")
	rn.LastAlarm = time.Now()
	for {

		if rn.Sm.state == LEADER {

			if time.Now().After(rn.LastAlarm.Add(time.Duration(rn.Sm.heartbeat_time_out*1) * time.Millisecond)) {
				rn.LastAlarm = time.Now()
				rn.TimeoutCh <- TIMEOUT{}
				//rn.debug_output3("L: ", time.Now())
			}
		} else {
			//debug_output(".")

			if time.Now().After(rn.LastAlarm.Add(time.Duration(rn.Sm.election_time_out*1) * time.Millisecond)) {
				rn.LastAlarm = time.Now()
				//debug_output("timeout fired")
				rn.TimeoutCh <- TIMEOUT{}
				//rn.debug_output2("timeout fired", "")
				//rn.debug_output3("F/C :", time.Now())
			}
		}

		if rn.StopSignal {
			//rn.debug_output2("stopping..timer", "")
			return
		}

	}
}
开发者ID:pratiksatapathy,项目名称:RAFT-VERSIONED-FILE-STORE,代码行数:32,代码来源:rn.go


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