Home > Back-end >  Run a Go routine indefinitely (restart when done)
Run a Go routine indefinitely (restart when done)

Time:07-02

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

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

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related