英文:
Polling two APIs in a single infinite for loop but with different delay
问题
我在服务器上有两个API,假设为API A和API B。我想每3秒调用一次API A,每200秒调用一次API B。我已经按照以下结构编写了程序:
- Main:处理身份验证并处理API调用。
- API-A:调用API A并处理其数据。
- 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:
- Main: that handles authentication and handles API calls.
- API-A: that calls API A and processes its data
- 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 <-aTicker.C:
callApiA()
case <-bTicker.C:
callApiB()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论