how to update reactive functions at a given time and not on a timer?

I want the running shiny application to update the data at the specified time, every time the minutes in the system are multiples of 15 (for example: 12:00, 12:15, 12:30, 12:45, 13:00, 13:15 etc). I currently use a reactive timer that fires every 15 minutes, but that doesn't solve my problem. How can I update the application only at the moment when the system time becomes a multiple of 15?

Upvotes: 0

Views: 319

Answers (1)

beerda
beerda

Reputation: 110

Get the current time, determine the amount of time until the next refresh, and call invalidateLater() appropriately.

For instance, the following shiny app refreshes the clock on each multiple of 15 seconds:

library(shiny)

ui <- fluidPage(
    mainPanel(
        textOutput('time')
    )
)

server <- function(input, output) {
    output$time <- renderText({
        time <- as.integer(format(Sys.time(), "%S"))
        invalidateLater((15 - time %% 15) * 1000)
        format(Sys.time(), "%H:%M:%S")
    })
}

shinyApp(ui = ui, server = server)

EDIT: I have simplified slightly the computation since the last edit. time <- as.integer(format(Sys.time(), "%S")) simply gets the second-part of current time. We compute this amount of seconds MODULO 15 (time %% 15) to obtain the number of seconds after last 15s multiple. We then subtract that value from 15 to obtain the number of seconds until the next multiple. Since the time must be in milliseconds, we multiply the result by 1000.

Upvotes: 2

Related Questions