當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang time.Ticker.Stop()用法及代碼示例

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的NewTicker()函數用於禁用股票行情指示器。因此,在調用Stop()方法之後,將不再發送任何引號。並且它不會關閉通道,以防止同時從通道讀取go-routine從而查看錯誤的“tick”。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func (t *Ticker) Stop()

在這裏,“t”是指向股票行情指示器的指針。在這裏,股票代號用於保持一個通道,該通道間隔提供時鍾的“滴答聲”。

返回值:它在調用Stop()方法之前返回指定操作的輸出,因為在調用它之後,代碼關閉。

例:

// Golang program to illustrate the usage of 
// time.Ticker.Stop() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import "fmt"
import "time"
  
// Calling main 
func main() { 
  
    // Calling NewTicker method 
    Ticker:= time.NewTicker(2 * time.Second) 
  
    // Creating channel using make 
    // keyword 
    mychannel:= make(chan bool) 
  
    // Go function 
    go func() { 
  
        // Using for loop 
        for { 
  
            // Select statement 
            select { 
  
            // Case statement 
            case <-mychannel:
                return
  
            // Case to print current time 
            case tm := <-Ticker.C:
                fmt.Println("The Current time is:", tm) 
            } 
        } 
    }() 
  
    // Calling Sleep() method 
    time.Sleep(7 * time.Second) 
  
    // Calling Stop() method 
    Ticker.Stop() 
  
    // Setting the value of channel 
    mychannel <- true
  
    // Printed when the ticker is turned off 
    fmt.Println("Ticker is turned off!") 
}

輸出:

The Current time is: 2020-04-09 07:26:05.374436607 +0000 UTC m=+2.000213251
The Current time is: 2020-04-09 07:26:07.374442201 +0000 UTC m=+4.000218858
The Current time is: 2020-04-09 07:26:09.374511648 +0000 UTC m=+6.000288424
Ticker is turned off!

在這裏,首先創建一個股票代號,然後創建一個發送時間的通道。在使用for循環以打印當前時間之後,將調用Ticker.Stop()方法並關閉股票行情指示器。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.Ticker.Stop() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。