función time.Ticker.Stop() en Golang con ejemplos

En el lenguaje Go, los paquetes de tiempo brindan funcionalidad para determinar y ver el tiempo. La función Stop() en el lenguaje Go se usa para deshabilitar un ticker. Entonces, después de llamar al método Stop(), no se transmitirán más ticks. Y no cierra el canal, para evitar que una lectura de rutina simultánea del canal vea un «tick» inexacto. Además, esta función se define en el paquete de tiempo. Aquí, debe importar el paquete «tiempo» para usar estas funciones. 

Sintaxis:

func (t *Ticker) Stop()

Aquí, “t” es un puntero al Ticker. El Ticker se utiliza para mantener un canal que proporciona ‘ticks’ de un reloj a intervalos. 

Valor devuelto: Devuelve el resultado de la operación indicada antes de llamar al método stop() porque después de llamarlo, el ticker se apaga. 

Ejemplo: 

C

// 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!")
}

Producción:

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!

Aquí, primero se crea un Ticker, luego se crea un canal que transmite el tiempo. Después de eso, se usa un bucle para imprimir la hora actual, luego se llama al método Ticker.Stop() y se apaga el ticker.

Publicación traducida automáticamente

Artículo escrito por nidhi1352singh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *