如何定期从 REST API 获取数据?

How to fetch data from REST API periodically?

背景

我目前正在构建一个“数据记录器”——使用 R Shiny 的应用程序。我确实有一个 REST - API,其中 returns 是一个随时间变化的值。我的目标是创建一个闪亮的应用程序,用户可以在其中单击操作按钮开始将从 api 获取的值定期(例如每 60 秒)写入数据框。当用户点击另一个操作按钮时,数据的记录也应该停止。

问题

我的问题是编写一个函数,该函数在按下按钮时开始执行,之后定期执行,并在按下另一个按钮时停止执行。

以前的想法

我之前尝试过使用 invalidateLater(),但我无法实现我想要的。

你们能帮我出个聪明的主意吗?

提前致谢!

这应该显示它是如何工作的。 invalidateLater()是正确的选择。 start/stop 按钮更改决定轮询是打开还是关闭的反应式表达式。这样,反应式 RestPoll 表达式在每次切换 on/off 时都会收到通知,当然,只要 Running() == TRUE.

500 毫秒后
library(shiny)

ui <- fluidPage(
  actionButton("btnStart", "Start"),
  actionButton("btnStop", "Stop"),
  textOutput("outTime")
)

server <- function(input, output, session) {
  Running <- reactiveVal(FALSE) 
  
  observeEvent(input$btnStart, {
    Running(TRUE)
  })

  observeEvent(input$btnStop, {
    Running(FALSE)
  })
  
  RestPoll <- reactive({
    if (Running()) # IS called every time `Running` changes
      invalidateLater(500, session)
    
    # Add any REST calls here, process the results
    
    return(Sys.time()) # deliver results
  })
  
  output$outTime <- renderText({
    req(RestPoll())
  })
}

shinyApp(ui, server)

您也可以使用 reactiveTimer 来做到这一点,但这也会在不需要轮询时轮询并使用资源。