Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run a Go routine indefinitely (restart when done)

I am rewriting my TypeScript projects to Golang and I encountered a problem:

I am running a for loop which starts up async workers on program load. If I understood correctly Go routines are a way to run async code concurrently. What I’d like to do is restart the function once it is done, indefinitely.

In TypeScript it looks something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async function init() {
  const count = async Users.getCount();

  // run all workers concurrently
  for (let i = 0; i < count; i += PER_WORKER) {
    const id = i / PER_WORKER;
    worker(id);
  }
}

async worker(id: number) {
  await new Promise((resolve) => {
    // do stuff
    resolve();
  })

  // restart function
  worker(workerId);
}

in Go I have pretty similar stuff, but when re-calling the function inside it just makes a mess? I thought of running the function by interval but I cannot know in advance the time it takes…

Thank you
NVH

>Solution :

What I’d like to do is restart the function once it is done, indefinitely.

You need a forever loop, of course:

for {
    f()
}

If you want to spin off the forever loop itself, put that in a function and invoke it with go:

go func loopCallingF() {
    for {
        f()
    }
}()

That is, we spin off the for loop itself; the for loop calls our function once each time. Doing this:

for {
    go f()
}

is wrong because that spins off f() an infinite number of times, as fast as it can, without waiting for f() to return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading