當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Time.Add方法代碼示例

本文整理匯總了Golang中Time.Time.Add方法的典型用法代碼示例。如果您正苦於以下問題:Golang Time.Add方法的具體用法?Golang Time.Add怎麽用?Golang Time.Add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Time.Time的用法示例。


在下文中一共展示了Time.Add方法的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: CleanDir

// CleanDir removes binary files under rundir in case they were not
// accessed for more than CleanFileDelay nanoseconds.  A last-cleaned
// marker file is created so that the next verification is only done
// after CleanFileDelay nanoseconds.
func CleanDir(rundir string, now time.Time) error {
	cleanedfile := filepath.Join(rundir, "last-cleaned")
	cleanLine := now.Add(-CleanFileDelay)
	if info, err := os.Stat(cleanedfile); err == nil && info.ModTime().After(cleanLine) {
		// It's been cleaned recently.
		return nil
	}
	f, err := os.Create(cleanedfile)
	if err != nil {
		return err
	}
	_, err = f.Write([]byte(now.Format(time.RFC3339)))
	f.Close()
	if err != nil {
		return err
	}

	// Look for expired files.
	d, err := os.Open(rundir)
	if err != nil {
		return err
	}
	infos, err := d.Readdir(-1)
	for _, info := range infos {
		atim := atime(info)
		access := time.Unix(int64(atim.Sec), int64(atim.Nsec))
		if access.Before(cleanLine) {
			os.Remove(filepath.Join(rundir, info.Name()))
		}
	}
	return nil
}
開發者ID:henrylee2cn,項目名稱:gorun,代碼行數:36,代碼來源:gorun.go

示例3: CreateTimeLimitCode

// create a time limit code
// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
	format := "200601021504"

	var start, end time.Time
	var startStr, endStr string

	if startInf == nil {
		// Use now time create code
		start = time.Now()
		startStr = start.Format(format)
	} else {
		// use start string create code
		startStr = startInf.(string)
		start, _ = time.ParseInLocation(format, startStr, time.Local)
		startStr = start.Format(format)
	}

	end = start.Add(time.Minute * time.Duration(minutes))
	endStr = end.Format(format)

	// create sha1 encode string
	sh := sha1.New()
	sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
	encoded := hex.EncodeToString(sh.Sum(nil))

	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
	return code
}
開發者ID:gigforks,項目名稱:gogs,代碼行數:30,代碼來源:tool.go

示例4: loadStacktrace

func (ss *StacktraceSource) loadStacktrace() {
	var lastUpdated time.Time
	var size int = 512
	var i int = 0
	var stacktrace []byte
	for {
		select {
		case ret := <-ss.getStacktraceRec:
			now := time.Now()
			if now.After(lastUpdated.Add(2 * time.Second)) {
				for {
					stacktrace = make([]byte, size)
					i = runtime.Stack(stacktrace, true)
					if i == size {
						size = int(float64(size) * 1.5)
						continue
					}
					size = int(float64(i) * 1.25)
					break
				}
				lastUpdated = now
			}
			ret <- StacktraceRecord{stacktrace[:i], lastUpdated}
		}
	}
}
開發者ID:jmptrader,項目名稱:goinfo,代碼行數:26,代碼來源:stacktrace.go

示例5: nextHousekeeping

// Determine when the next housekeeping should occur.
func (self *containerData) nextHousekeeping(lastHousekeeping time.Time) time.Time {
	if *allowDynamicHousekeeping {
		stats, err := self.storageDriver.RecentStats(self.info.Name, 2)
		if err != nil {
			if self.allowErrorLogging() {
				glog.Warningf("Failed to get RecentStats(%q) while determining the next housekeeping: %v", self.info.Name, err)
			}
		} else if len(stats) == 2 {
			// TODO(vishnuk): Use no processes as a signal.
			// Raise the interval if usage hasn't changed in the last housekeeping.
			if stats[0].StatsEq(stats[1]) && (self.housekeepingInterval < *maxHousekeepingInterval) {
				self.housekeepingInterval *= 2
				if self.housekeepingInterval > *maxHousekeepingInterval {
					self.housekeepingInterval = *maxHousekeepingInterval
				}
				glog.V(3).Infof("Raising housekeeping interval for %q to %v", self.info.Name, self.housekeepingInterval)
			} else if self.housekeepingInterval != *HousekeepingInterval {
				// Lower interval back to the baseline.
				self.housekeepingInterval = *HousekeepingInterval
				glog.V(3).Infof("Lowering housekeeping interval for %q to %v", self.info.Name, self.housekeepingInterval)
			}
		}
	}

	return lastHousekeeping.Add(self.housekeepingInterval)
}
開發者ID:rjnagal,項目名稱:cadvisor,代碼行數:27,代碼來源:container.go

示例6: createPayload

func createPayload(payload Payload, token string, id uint32, now time.Time) (*rawPayload, error) {
	p := &rawPayload{id: id, created: now}

	// prepare binary payload from JSON structure
	bpayload, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	// decode hexadecimal push device token to binary byte array
	btoken, err := hex.DecodeString(token)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error decoding token: %v. Error: %v", token, err))
	}

	buffer := make([]byte, 1+4+4+2+len(btoken)+2+len(bpayload))

	// build the actual pdu
	buffer[0] = uint8(1)                                                        // command
	binary.BigEndian.PutUint32(buffer[1:], id)                                  // transaction id, optional
	binary.BigEndian.PutUint32(buffer[5:], uint32(now.Add(1*time.Hour).Unix())) // expiration time, 1 hour
	binary.BigEndian.PutUint16(buffer[9:], uint16(len(btoken)))                 // push device token
	copy(buffer[11:], btoken)                                                   //
	binary.BigEndian.PutUint16(buffer[11+len(btoken):], uint16(len(bpayload)))  // push payload
	copy(buffer[11+len(btoken)+2:], bpayload)                                   //

	p.data = buffer

	return p, nil
}
開發者ID:ryanslade,項目名稱:apns,代碼行數:30,代碼來源:payload.go

示例7: CreateTimeLimitCode

// create a time limit code
// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
	format := "YmdHi"

	var start, end time.Time
	var startStr, endStr string

	if startInf == nil {
		// Use now time create code
		start = time.Now()
		startStr = DateFormat(start, format)
	} else {
		// use start string create code
		startStr = startInf.(string)
		start, _ = DateParse(startStr, format)
		startStr = DateFormat(start, format)
	}

	end = start.Add(time.Minute * time.Duration(minutes))
	endStr = DateFormat(end, format)

	// create sha1 encode string
	sh := sha1.New()
	sh.Write([]byte(data + SecretKey + startStr + endStr + ToStr(minutes)))
	encoded := hex.EncodeToString(sh.Sum(nil))

	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
	return code
}
開發者ID:Julianzz,項目名稱:gogs,代碼行數:30,代碼來源:tool.go

示例8: rescale

/*
A common feature of the above techniques—indeed, the key technique that
allows us to track the decayed weights efficiently—is that they maintain
counts and other quantities based on g(ti − L), and only scale by g(t − L)
at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero
and one, the intermediate values of g(ti − L) could become very large. For
polynomial functions, these values should not grow too large, and should be
effectively represented in practice by floating point values without loss of
precision. For exponential functions, these values could grow quite large as
new values of (ti − L) become large, and potentially exceed the capacity of
common floating point types. However, since the values stored by the
algorithms are linear combinations of g values (scaled sums), they can be
rescaled relative to a new landmark. That is, by the analysis of exponential
decay in Section III-A, the choice of L does not affect the final result. We
can therefore multiply each value based on L by a factor of exp(−α(L′ − L)),
and obtain the correct value as if we had instead computed relative to a new
landmark L′ (and then use this new L′ at query time). This can be done with
a linear pass over whatever data structure is being used.
*/
func (s *exponentiallyDecayingSample) rescale(now time.Time) {
	s.nextScaleTime = now.Add(edRescaleThreshold)
	oldStartTime := s.startTime
	s.startTime = now
	scale := math.Exp(-s.alpha * s.startTime.Sub(oldStartTime).Seconds())
	s.values.ScalePriority(scale)
}
開發者ID:couchbasedeps,項目名稱:go-metrics-1,代碼行數:26,代碼來源:edsample.go

示例9: checkTokenWithTime

// checkTokenWithTime checks token using the given time.
func checkTokenWithTime(c context.Context, token, user, action string, now time.Time) error {
	if token == "" {
		return fmt.Errorf("token is not given")
	}
	d, err := base64.URLEncoding.DecodeString(token)
	sig := &sigData{}
	if err = json.Unmarshal(d, sig); err != nil {
		return err
	}

	issueTime := time.Unix(0, sig.IssueTime)
	if now.Sub(issueTime) >= Timeout {
		return fmt.Errorf("signature has already expired")
	}
	if issueTime.After(now.Add(validFuture)) {
		return fmt.Errorf("token come from future")
	}

	toVerify := toData(user, action, sig.IssueTime)

	certs, err := signature.PublicCerts(c)
	if err != nil {
		return err
	}
	cert := signature.X509CertByName(certs, sig.Key)
	if cert == nil {
		return fmt.Errorf("cannot find cert")
	}

	return signature.Check(toVerify, cert, sig.Signature)
}
開發者ID:shishkander,項目名稱:luci-go,代碼行數:32,代碼來源:xsrf.go

示例10: DialTCPSAddrTimeout

// DialTCPSAddrTimeout 同 DialTCPSAddr 函數,增加了超時功能
func (p *directProxyClient) DialTCPSAddrTimeout(network string, raddr string, timeout time.Duration) (rconn ProxyTCPConn, rerr error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
	default:
		return nil, fmt.Errorf("不支持的 network 類型:%v", network)
	}
	d := net.Dialer{Timeout: timeout, LocalAddr: &p.TCPLocalAddr}
	conn, err := d.Dial(network, raddr)
	if err != nil {
		return nil, err
	}

	splitHttp := false
	if p.splitHttp {
		raddr, err := net.ResolveTCPAddr(network, raddr)
		if err == nil && raddr.Port == 80 {
			splitHttp = true
		}
	}
	wTime := time.Time{}
	if p.sleep != 0 {
		wTime = time.Now()
		wTime = wTime.Add(p.sleep)
	}

	if tcpConn, ok := conn.(*net.TCPConn); ok {
		return &directTCPConn{*tcpConn, splitHttp, wTime, p}, nil
	}
	return nil, fmt.Errorf("內部錯誤")
}
開發者ID:GameXG,項目名稱:ProxyClient,代碼行數:31,代碼來源:directproxy.go

示例11: UpdateEliminationSchedule

// Incrementally creates any elimination matches that can be created, based on the results of alliance
// selection or prior elimination rounds. Returns the winning alliance once it has been determined.
func (database *Database) UpdateEliminationSchedule(startTime time.Time) ([]AllianceTeam, error) {
	alliances, err := database.GetAllAlliances()
	if err != nil {
		return []AllianceTeam{}, err
	}
	winner, err := database.buildEliminationMatchSet(1, 1, len(alliances))
	if err != nil {
		return []AllianceTeam{}, err
	}

	// Update the scheduled time for all matches that have yet to be run.
	matches, err := database.GetMatchesByType("elimination")
	if err != nil {
		return []AllianceTeam{}, err
	}
	matchIndex := 0
	for _, match := range matches {
		if match.Status == "complete" {
			continue
		}
		match.Time = startTime.Add(time.Duration(matchIndex*elimMatchSpacingSec) * time.Second)
		database.SaveMatch(&match)
		matchIndex++
	}

	return winner, err
}
開發者ID:Team254,項目名稱:cheesy-arena,代碼行數:29,代碼來源:elimination_schedule.go

示例12: updateNextAllowedIncrease

func (m *MaxReplicationLagModule) updateNextAllowedIncrease(now time.Time, increase float64, key string) {
	minDuration := m.config.MinDurationBetweenChanges()
	// We may have to wait longer than the configured minimum duration
	// until we see an effect of the increase.
	// Example: If the increase was fully over the capacity, it will take
	// 1 / increase seconds until the replication lag goes up by 1 second.
	// E.g.
	// (If the system was already at its maximum capacity (e.g. 1k QPS) and we
	// increase the rate by e.g. 5% to 1050 QPS, it will take 20 seconds until
	// 1000 extra queries are buffered and the lag increases by 1 second.)
	// On top of that, add 2 extra seconds to account for a delayed propagation
	// of the data (because the throttler takes over the updated rate only every
	// second and it publishes its rate history only after a second is over).
	// TODO(mberlin): Instead of adding 2 seconds, should we wait for twice the
	// calculated time instead?
	minPropagationTime := time.Duration(1.0/increase+2) * time.Second
	if minPropagationTime > minDuration {
		minDuration = minPropagationTime
	}
	if minDuration > m.config.MaxDurationBetweenIncreases() {
		// Cap the rate to a reasonable amount of time (very small increases may
		// result into a 20 minutes wait otherwise.)
		minDuration = m.config.MaxDurationBetweenIncreases()
	}
	m.nextAllowedIncrease = now.Add(minDuration)
	m.replicaUnderIncreaseTest = key
}
開發者ID:erzel,項目名稱:vitess,代碼行數:27,代碼來源:max_replication_lag_module.go

示例13: makeWindows

func (w Window) makeWindows(left, right TimeShiftFunc) []Window {
	var ws []Window
	if w.From.After(w.Until) {
		return ws
	}
	var start, end time.Time
	from := w.From
	for {
		switch {
		case len(ws) == 0:
			start = now.New(w.From).BeginningOfDay()
		default:
			start = left(from)
		}
		end = right(from)
		if end.After(w.Until) {
			// discard end and use the end of day of until
			ws = append(ws, Window{From: start, Until: now.New(w.Until).EndOfDay()})
			break
		}
		ws = append(ws, Window{From: start, Until: end})
		from = end.Add(oneDay)
	}
	return ws
}
開發者ID:ubleipzig,項目名稱:oaimi,代碼行數:25,代碼來源:intervals.go

示例14: MakeCookie

func (p *OauthProxy) MakeCookie(req *http.Request, value string, expiration time.Duration, now time.Time) *http.Cookie {
	domain := req.Host
	if h, _, err := net.SplitHostPort(domain); err == nil {
		domain = h
	}
	if p.CookieDomain != "" {
		if !strings.HasSuffix(domain, p.CookieDomain) {
			log.Printf("Warning: request host is %q but using configured cookie domain of %q", domain, p.CookieDomain)
		}
		domain = p.CookieDomain
	}

	if value != "" {
		value = cookie.SignedValue(p.CookieSeed, p.CookieName, value, now)
	}
	return &http.Cookie{
		Name:     p.CookieName,
		Value:    value,
		Path:     "/",
		Domain:   domain,
		HttpOnly: p.CookieHttpOnly,
		Secure:   p.CookieSecure,
		Expires:  now.Add(expiration),
	}
}
開發者ID:jrallison,項目名稱:oauth2_proxy,代碼行數:25,代碼來源:oauthproxy.go

示例15: TimeSince

/** 微博時間格式化顯示
 * @param timestamp,標準時間戳
 */
func TimeSince(created time.Time) string {

	//減去8小時
	d, _ := time.ParseDuration("-8h")
	t := created.Add(d)

	since := int(time.Since(t).Minutes())
	output := ""
	switch {
	case since < 0:
		output = fmt.Sprintf("穿越了 %d 分鍾..", -since)
	case since < 1:
		output = "剛剛" //"小於 1 分鍾"
	case since < 60:
		output = fmt.Sprintf("%d 分鍾之前", since)
	case since < 60*24:
		output = fmt.Sprintf("%d 小時之前", since/(60))
	case since < 60*24*30:
		output = fmt.Sprintf("%d 天之前", since/(60*24))
	case since < 60*24*365:
		output = fmt.Sprintf("%d 月之前", since/(60*24*30))
	default:
		output = fmt.Sprintf("%d 年之前", since/(60*24*365))
	}
	return output
}
開發者ID:rose312,項目名稱:mzr,代碼行數:29,代碼來源:helper.go


注:本文中的Time.Time.Add方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。