當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。