在单个无限循环中轮询两个不同延迟的API

huangapple go评论91阅读模式
英文:

Polling two APIs in a single infinite for loop but with different delay

问题

我在服务器上有两个API,假设为API A和API B。我想每3秒调用一次API A,每200秒调用一次API B。我已经按照以下结构编写了程序:

  1. Main:处理身份验证并处理API调用。
  2. API-A:调用API A并处理其数据。
  3. API-B:调用API B并处理其数据。

有人可以告诉我如何在一个程序(Main)中实现这两个API调用吗?我现在正在使用一个for循环来调用API A,并将其休眠3秒,现在我想将API B与其休眠条件结合起来。

我希望它们两个同时运行,并按照各自的条件工作,同时它们都在一个程序中运行,因为Main已经处理了身份验证,我不想为这两个API创建两个单独的程序。

英文:

I have two APIs on a server. Let's say API A and API B. I want to call API A every 3 seconds and API B every 200 seconds. I have coded the program in the following structure:

  1. Main: that handles authentication and handles API calls.
  2. API-A: that calls API A and processes its data
  3. API-B: that calls API B and processes its data.

Can anyone tell me how can I implement both of the API calls in a single program (Main). I am running a single for loop for API A with sleeping it for 3 seconds now I want to fit the API B with its condition of sleeping.

I want both of them to run simultaneously with their condition, while both be working in one program, main as it is handling authentication and I don't want to make two seperate programs for these two APIs.

答案1

得分: 2

你可以设置两个计时器,并在循环中等待两个通道上的事件。

aTicker := time.NewTicker(time.Second * 3)
bTicker := time.NewTicker(time.Second * 200)
for {
  select {
    case <-aTicker.C:
      调用API A()
    case <-bTicker.C:
      调用API B()
  }
}
英文:

You can set up two timers and wait for events on both channels in a loop.

aTicker := time.NewTicker(time.Second * 3)
bTicker := time.NewTicker(time.Second * 200)
for {
  select {
    case &lt;-aTicker.C:
      callApiA()
    case &lt;-bTicker.C:
      callApiB()
  }
}

huangapple
  • 本文由 发表于 2022年4月16日 15:52:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/71892080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定