K
K
Kirill Novak2021-04-21 15:02:13
go
Kirill Novak, 2021-04-21 15:02:13

How to make in Go that some goroutine is executed cyclically until state becomes false?

I tried to write something similar, but it seems to me that it will not always work correctly. Can you please tell me how this can be done without global variables? Purely, so that the function is in itself.

func doSomethingEvery5Seconds(ch chan bool) {
  log.Println("Started!")
  for <-ch {
    log.Println("I am doing this!")
    time.Sleep(5 * time.Second)
    ch <- true
  }
}

func main() {
  ch := make(chan bool, 1)
  ch <- true
  go doSomethingEvery5Seconds(ch)
  time.Sleep(15 * time.Second)
  ch <- false // Останавливаем спустя 15 секунд
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2021-04-21
@kinojs

In your implementation, the inscription "I am doing this!" will be shown only once, because you write only 1 time to the channel, and then the execution will block on reading data from the channel, because there will be no data.
What you want to do can be done like this:

package main

import (
    "log"
    "time"
)

func doSomethingEvery5Seconds(ch chan bool) {
    log.Println("Started!")
    for {
        select {
        case <-ch:
            return
        default:
            log.Println("I am doing this!")
            time.Sleep(1 * time.Second)
        }
    }
}

func main() {
    ch := make(chan bool, 1)
    go doSomethingEvery5Seconds(ch)
    time.Sleep(15 * time.Second)
    close(ch) // Останавливаем спустя 15 секунд
}

R
Romses Panagiotis, 2021-04-21
@romesses

Here is an example of working with a pendulum:
https://gobyexample.com/tickers
Similar to what Evgeny Mamonov pointed out , but instead time.Sleep(1 * time.Second)of the value, they are taken from the pendulum channel, which will be blocked for the specified time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question