vertesy / Rocinante

A collection of custom R functions. Helper functions complementing CodeAndRoll2.
https://vertesy.github.io/Rocinante/
GNU General Public License v3.0
1 stars 1 forks source link

Mimic the behavior of the "Suspend Session" button in the posit dashboard of RStudio Server GUI programmatically #5

Open vertesy opened 7 months ago

vertesy commented 7 months ago

Describe the solution you'd like To mimic the behavior of the "Suspend Session" button in the RStudio RStudio GUI programmatically, you would generally interact with RStudio Server's internal mechanisms or use its API, to performs exactly the same action as the "Suspend Session" button in the RStudio GUI, which suspends the session and allows you to resume it later from the "Sessions" list in the Posit Workbench.

A workaround approach involves using system-level commands to interact with RStudio Server's management commands Read more

vertesy commented 7 months ago
file.edit("~/GitHub/Packages/Rocinante/Development/quit.session.later.DEV.R")
# Schedule a task to quit the R session at a specific time without needing a background job
# Install the later package if not already installed: install.packages("later")

library(later)

# Function to quit the R session
quit_session <- function() {
  (proj <- CodeAndRoll2::getProject())
  (date <- Stringendo::idate(Format = "%Y.%m.%d_%H.%M"))
  gc()
  session_name <- kpp("session", date, proj, "Rdata")
  save.image(file = session_name) # Optional: save session before quitting
  q("no") # Quit without saving (since we already saved manually)
}

# Schedule the session to quit at 09:20 AM on the current day
# Note: This assumes your R session and your system's time zone are the same
schedule_at <- function(target_hour, target_min, fun) {
  now <- Sys.time()
  target_time <- as.POSIXct(format(now, "%Y-%m-%d"), tz = attr(now, "tzone"))
  target_time <- target_time + hours(target_hour) + minutes(target_min)
  delay <- as.numeric(difftime(target_time, now, units = "secs"))

  if (delay < 0) {
    # Target time has passed for today, schedule for next day
    delay <- delay + 24 * 60 * 60
  }

  later(fun, delay)
}

# Example usage: Quit R session at 09:20 AM
schedule_at(9, 20, quit_session)