当前位置: 首页>>代码示例>>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;未经允许,请勿转载。