本文整理汇总了Golang中Time.Duration.String方法的典型用法代码示例。如果您正苦于以下问题:Golang Duration.String方法的具体用法?Golang Duration.String怎么用?Golang Duration.String使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Duration
的用法示例。
在下文中一共展示了Duration.String方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: saveUpgradeData
func saveUpgradeData(opts *Upgradeable, ulog string, duration time.Duration) error {
log.Debugf("%s in (%s)\n%s",
cmd.Colorfy(opts.B.GetFullName(), "cyan", "", "bold"),
cmd.Colorfy(duration.String(), "green", "", "bold"),
cmd.Colorfy(ulog, "yellow", "", ""))
return nil
}
示例2: ImageSetMembers
func (c *Client) ImageSetMembers(imageset *ImageSet, timeout time.Duration) (result []*Image, err error) {
chImages := make(chan *Image)
for _, member := range imageset.Members {
log.Println(len(imageset.Members), "images to get:", member.ID, c)
go func(url string) {
image, err := c.Image(url)
if err != nil {
return
}
chImages <- image
}(member.ID)
}
images := []*Image{}
for {
select {
case image := <-chImages:
log.Println("Received:", image.ID)
images = append(images, image)
if len(images) == len(imageset.Members) {
return images, nil
}
case <-time.After(timeout):
if timeout > time.Duration(0) {
return nil, fmt.Errorf("Image retrieval timed out after %sms", timeout.String())
}
}
}
}
示例3: StreamAppLogs
func (c *Client) StreamAppLogs(app, filter string, follow bool, since time.Duration, output io.WriteCloser) error {
return c.Stream(fmt.Sprintf("/apps/%s/logs", app), map[string]string{
"Filter": filter,
"Follow": fmt.Sprintf("%t", follow),
"Since": since.String(),
}, nil, output)
}
示例4: StreamRackLogs
// StreamRackLogs streams the logs for a Rack
func (c *Client) StreamRackLogs(filter string, follow bool, since time.Duration, output io.WriteCloser) error {
return c.Stream("/system/logs", map[string]string{
"Filter": filter,
"Follow": fmt.Sprintf("%t", follow),
"Since": since.String(),
}, nil, output)
}
示例5: SetDuration
// SetDuration adds or modifies the configuration for a given duration at a
// specific key.
func (c *Config) SetDuration(key string, value time.Duration) {
c.mu.RLock()
{
c.m[key] = value.String()
}
c.mu.RUnlock()
}
示例6: saveDeployData
func saveDeployData(opts *DeployOpts, imageId, dlog string, duration time.Duration, deployError error) error {
log.Debugf("%s in (%s)\n%s",
cmd.Colorfy(opts.B.GetFullName(), "cyan", "", "bold"),
cmd.Colorfy(duration.String(), "green", "", "bold"),
cmd.Colorfy(dlog, "yellow", "", ""))
//if there are deployments to track as follows in outputs: {} then do it here.
//Riak: code to save the status of a deploy (created.)
// deploy :
// name:
// status:
/*deploy := DeployData {
App: opts.App.Name,
Timestamp: time.Now(),
Duration: duration,
Commit: opts.Commit,
Image: imageId,
Log: log,
}
if opts.Commit != "" {
deploy.Origin = "git"
} else if opts.Image != "" {
deploy.Origin = "rollback"
} else {
deploy.Origin = "app-deploy"
}
if deployError != nil {
deploy.Error = deployError.Error()
}
return db.Store(compid or assmid, &struct)
*/
return nil
}
示例7: saveLifecycleData
func saveLifecycleData(li *LifecycleOpts, llog string, elapsed time.Duration) error {
log.Debugf("%s in (%s)\n%s",
cmd.Colorfy(li.B.GetFullName(), "cyan", "", "bold"),
cmd.Colorfy(elapsed.String(), "green", "", "bold"),
cmd.Colorfy(llog, "yellow", "", ""))
return nil
}
示例8: SendReadTimeout
// SendReadTimeout instructs the peer to simulate a read timeout. It then waits
// for acknowledgement of the timeout, buffering any packets received since
// then. The packets are then returned.
func (p *packetAdaptor) SendReadTimeout(d time.Duration) ([][]byte, error) {
p.log("Simulating read timeout: "+d.String(), nil)
payload := make([]byte, 1+8)
payload[0] = opcodeTimeout
binary.BigEndian.PutUint64(payload[1:], uint64(d.Nanoseconds()))
if _, err := p.Conn.Write(payload); err != nil {
return nil, err
}
var packets [][]byte
for {
opcode, err := p.readOpcode()
if err != nil {
return nil, err
}
switch opcode {
case opcodeTimeoutAck:
p.log("Received timeout ACK", nil)
// Done! Return the packets buffered and continue.
return packets, nil
case opcodePacket:
// Buffer the packet for the caller to process.
packet, err := p.readPacketBody()
if err != nil {
return nil, err
}
p.log("Simulating dropped packet", packet)
packets = append(packets, packet)
default:
return nil, fmt.Errorf("unexpected opcode '%d'", opcode)
}
}
}
示例9: AddFooter
// TODO: Place at the bottom of the content instead of at the bottom of the window
func AddFooter(page *onthefly.Page, footerText, footerTextColor, footerColor string, elapsed time.Duration) (*onthefly.Tag, error) {
body, err := page.GetTag("body")
if err != nil {
return nil, err
}
div := body.AddNewTag("div")
div.AddAttrib("id", "notice")
div.AddStyle("position", "fixed")
div.AddStyle("bottom", "0")
div.AddStyle("left", "0")
div.AddStyle("width", "100%")
div.AddStyle("display", "block")
div.AddStyle("padding", "0")
div.AddStyle("margin", "0")
div.AddStyle("background-color", footerColor)
div.AddStyle("font-size", "0.6em")
div.AddStyle("text-align", "right")
div.AddStyle("box-shadow", "1px -2px 3px rgba(0,0,0, .5)")
innerdiv := div.AddNewTag("div")
innerdiv.AddAttrib("id", "innernotice")
innerdiv.AddStyle("padding", "0 2em 0 0")
innerdiv.AddStyle("margin", "0")
innerdiv.AddStyle("color", footerTextColor)
innerdiv.AddContent("Generated in " + elapsed.String() + " | " + footerText)
return div, nil
}
示例10: client
func client(wg *sync.WaitGroup, host string, port, len int, duration time.Duration, chStat chan int) {
defer func() {
if r := recover(); r != nil {
log.Printf("error: %s", r)
}
log.Printf("disconnected")
wg.Done()
}()
log.Printf("connecting to %s:%d, len %d, duration %s", host, port, len, duration.String())
conn, err := utp.DialTimeout(fmt.Sprintf("%s:%d", host, port), time.Second)
if err != nil {
panic(err)
}
defer conn.Close()
log.Printf("connected")
buf := bytes.Repeat([]byte("H"), len)
ts := time.Now()
for time.Since(ts) < duration {
n, err := conn.Write(buf)
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
chStat <- n
}
}
示例11: NewIngestionProcess
// NewIngestionProcess creates a Process for ingesting data.
func NewIngestionProcess(git *gitinfo.GitInfo, tileDir, datasetName string, ri ingester.ResultIngester, config map[string]string, every time.Duration, nCommits int, minDuration time.Duration, statusDir, metricName string) ProcessStarter {
return func() {
i, err := ingester.NewIngester(git, tileDir, datasetName, ri, nCommits, minDuration, config, statusDir, metricName)
if err != nil {
glog.Fatalf("Failed to create Ingester: %s", err)
}
glog.Infof("Starting %s ingester. Run every %s.", datasetName, every.String())
// oneStep is a single round of ingestion.
oneStep := func() {
glog.Infof("Running ingester: %s", datasetName)
err := i.Update()
if err != nil {
glog.Error(err)
}
glog.Infof("Finished running ingester: %s", datasetName)
}
// Start the ingester.
go func() {
oneStep()
for _ = range time.Tick(every) {
oneStep()
}
}()
}
}
示例12: bench
func bench(target string) {
fmt.Println("begin bench to: " + target + " ...")
succ := 0
fail := 0
var t time.Duration = 0
for i := 0; i < 10 || t.Seconds() < 30; i++ {
start := time.Now()
resp, err := net.NewHttpGet(target)
if err == nil {
defer resp.Close()
_, err := resp.ReadAll()
if err == nil {
succ++
end := time.Now()
t += end.Sub(start)
continue
}
}
fail++
}
fmt.Printf("succ: %d\n", succ)
if succ > 0 {
fmt.Println("used: " + t.String())
fmt.Println("avg: " + time.Duration(int64(t)/int64(succ)).String())
}
fmt.Printf("fail: %d\n", fail)
}
示例13: Deadman
// Helper function for creating an alert on low throughput, aka deadman's switch.
//
// - Threshold -- trigger alert if throughput drops below threshold in points/interval.
// - Interval -- how often to check the throughput.
// - Expressions -- optional list of expressions to also evaluate. Useful for time of day alerting.
//
// Example:
// var data = stream.from()...
// // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
// data.deadman(100.0, 10s)
// //Do normal processing of data
// data....
//
// The above is equivalent to this
// Example:
// var data = stream.from()...
// // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
// data.stats(10s)
// .derivative('collected')
// .unit(10s)
// .nonNegative()
// .alert()
// .id('node \'stream0\' in task \'{{ .TaskName }}\'')
// .message('{{ .ID }} is {{ if eq .Level "OK" }}alive{{ else }}dead{{ end }}: {{ index .Fields "collected" | printf "%0.3f" }} points/10s.')
// .crit(lamdba: "collected" <= 100.0)
// //Do normal processing of data
// data....
//
// The `id` and `message` alert properties can be configured globally via the 'deadman' configuration section.
//
// Since the AlertNode is the last piece it can be further modified as normal.
// Example:
// var data = stream.from()...
// // Trigger critical alert if the throughput drops below 100 points per 1s and checked every 10s.
// data.deadman(100.0, 10s).slack().channel('#dead_tasks')
// //Do normal processing of data
// data....
//
// You can specify additional lambda expressions to further constrain when the deadman's switch is triggered.
// Example:
// var data = stream.from()...
// // Trigger critical alert if the throughput drops below 100 points per 10s and checked every 10s.
// // Only trigger the alert if the time of day is between 8am-5pm.
// data.deadman(100.0, 10s, lambda: hour("time") >= 8 AND hour("time") <= 17)
// //Do normal processing of data
// data....
//
func (n *node) Deadman(threshold float64, interval time.Duration, expr ...tick.Node) *AlertNode {
dn := n.Stats(interval).
Derivative("emitted").NonNegative()
dn.Unit = interval
an := dn.Alert()
critExpr := &tick.BinaryNode{
Operator: tick.TokenLessEqual,
Left: &tick.ReferenceNode{
Reference: "emitted",
},
Right: &tick.NumberNode{
IsFloat: true,
Float64: threshold,
},
}
// Add any additional expressions
for _, e := range expr {
critExpr = &tick.BinaryNode{
Operator: tick.TokenAnd,
Left: critExpr,
Right: e,
}
}
an.Crit = critExpr
// Replace NODE_NAME with actual name of the node in the Id.
an.Id = strings.Replace(n.pipeline().deadman.Id(), nodeNameMarker, n.Name(), 1)
// Set the message on the alert node.
an.Message = strings.Replace(n.pipeline().deadman.Message(), intervalMarker, interval.String(), 1)
return an
}
示例14: Send
// Send will update the given body with the paramters expected by a Pandora server
// and return the Mid generated by the server or an error.
func (mb *Mailbox) Send(from, to string, delay time.Duration, body url.Values) (string, error) {
var msg pandora.Message
msg.Empty(body)
msg.SetSender(from)
msg.SetReceiver(to)
msg.SetClientTime(time.Now())
msg.Set("delay", delay.String())
res, err := mb.Client.PostForm(mb.BaseUrl+"/send", body)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("invalid status code: %v", res.StatusCode)
}
buf, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
values, err := url.ParseQuery(string(buf))
if err != nil {
return "", err
}
if len(values.Get("error")) > 0 {
return "", errors.New(values.Get("error"))
}
return values.Get("mid"), nil
}
示例15: Fetch
// Fetch asks for the server for a message
func (mb *Mailbox) Fetch(from string, lockFor time.Duration) (url.Values, error) {
// now, try to consume the message
msgToFetch := make(url.Values)
msgToFetch.Set(pandora.KeyReceiver, from)
msgToFetch.Set(pandora.KeyLeaseTime, lockFor.String())
res, err := mb.Client.PostForm(mb.BaseUrl+"/fetch", msgToFetch)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode == http.StatusNoContent {
return nil, ErrNoData
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("invalid status code: %v", res.StatusCode)
}
buf, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
respValues, err := url.ParseQuery(string(buf))
if err != nil {
return nil, err
}
if len(respValues.Get("mid")) == 0 {
return nil, fmt.Errorf("mid empty")
}
return respValues, nil
}