Start R Shiny app as a background job programmatically

Viewed 523

Dean Attali has provided a wonderful example on how to exit elegantly from a Shiny app using a close button which both closes the browser window and ends the Shiny session. Consider the following example (modification of the original code from Dean):

The ui.r:

library(shiny)
library(shinyjs)

jscode <- "shinyjs.closeWindow = function() { window.close(); }"

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = jscode, functions = c("closeWindow")),
  htmlOutput(outputId = "exitHeading"),
  actionButton(inputId = "closeGUI", label = "Exit")
)

The server.r:

library(shiny)
library(shinyjs)

server <- function(input, output, session) {
  output$exitHeading <- renderText("Press the button below to exit the app")
  observeEvent(input$closeGUI, {
    js$closeWindow()
    stopApp()
  })
}

And running the app:

runApp(appDir = "/tmp")

My question is about how to start a Shiny app as a background job programmatically, so that the RStudio console is free for further use (or even start a second Shiny app in parallel) while the app is still running, and then end the job using the exit button from the app above. I am looking for a solution which can be added to a package which contains a Shiny app, like this one.

I have read this and have tried the provided sample app, but it still requires manual intervention by the user.

Can someone assist with this?

1 Answers

So as I mentioned in the comments you can achieve this by using the system which basically runs a terminal command, with the wait and show.output.on.console flags set to FALSE.

system('Rscript file.r', wait=F, show.output.on.console = F)
# if you want to access a file from in a package u need
# also in the source of the package you need to put the
# folder `directory` in `root.of.package/inst`
p <- system.file(file.path("directory", "myfile.r"), package = "my.package")
system(paste0('Rscript "', p, '"'), wait=F)
Related