Mr.KT
Mr.KT

Reputation: 23

Is there an R function to run a piece of code multiple times with 3 seconds interval

I have a code snippet to get data from a MYSQL database table. I would like to continue refreshing the dataframe for every 3 seconds.

library(RMySQL)
library(dbConnect)
library(tictoc)

mydb = dbConnect(MySQL(), user='root', password='password', dbname='test_data', host='localhost')

dbListTables(mydb)

rs = dbSendQuery(mydb, "select * from rawdata")

data = fetch(rs)

View(data)

Is there an R function like "ReactiveFileReader" to work with a database engine ? Or would you please help with a code snippet to run this code multiple times for every 3 seconds. Thanks

Upvotes: 0

Views: 164

Answers (2)

Lorenzo Negri
Lorenzo Negri

Reputation: 51

One thing you can do is to have a function to run every n times with delay, but the problem is that the data will be stored for every replication so it can become very big soon:

f <- function(){
    Sys.sleep(3)#delay time here
    mydb = dbConnect(MySQL(), user='root', password='password', dbname='test_data', host='localhost')
    dbListTables(mydb)
    rs = dbSendQuery(mydb, "select * from rawdata")
    fetch(rs)
}

# use replicate to run the function n times with delay time
data <- replicate(10, f())

we will get data as a vector with all delayed queries, or a matrix of vectors.

Upvotes: 0

r2evans
r2evans

Reputation: 160597

I'll adapt the example from shiny::reactiveTimer. Tested on my database/instance (not RMySQL, but close enough).

library(DBI)
library(shiny)

ui <- fluidPage(
  tableOutput("mytbl")
)

server <- function(input, output) {
  # Anything that calls autoInvalidate will automatically invalidate
  # every 2 seconds.
  autoInvalidate <- reactiveTimer(3000)

  mydb = dbConnect(RMySQL::MySQL(), user='root', password='password', dbname='test_data', host='localhost')

  mydat <- eventReactive(autoInvalidate(), {
    DBI::dbGetQuery(mydb, "select * from rawdata")
  })

  output$mytbl <- renderTable(mydat())
}

Upvotes: 1

Related Questions