我从R Shiny Gallery获取此代码:http://shiny.rstudio.com/gallery/reactive-poll-and-file-reader.html
function(input, output, session) {
# Create a random name for the log file
logfilename <- paste0('logfile',
floor(runif(1, 1e+05, 1e+06 - 1)),
'.txt')
# ============================================================
# This part of the code writes to the log file every second.
# Writing to the file could be done by an external process.
# In this example, we'll write to the file from inside the app.
logwriter <- observe({
# Invalidate this observer every second (1000 milliseconds)
invalidateLater(1000, session)
# Clear log file if more than 10 entries
if (file.exists(logfilename) &&
length(readLines(logfilename)) > 10) {
unlink(logfilename)
}
# Add an entry to the log file
cat(as.character(Sys.time()), '\n', file = logfilename,
append = TRUE)
})
# When the client ends the session, suspend the observer and
# remove the log file.
session$onSessionEnded(function() {
logwriter$suspend()
unlink(logfilename)
})
# ============================================================
# This part of the code monitors the file for changes once per
# 0.5 second (500 milliseconds).
fileReaderData <- reactiveFileReader(500, session,
logfilename, readLines)
output$fileReaderText <- renderText({
# Read the text, and make it a consistent number of lines so
# that the output box doesn't grow in height.
text <- fileReaderData()
length(text) <- 14
text[is.na(text)] <- ""
paste(text, collapse = '\n')
})
# ============================================================
# This part of the code monitors the file for changes once
# every four seconds.
pollData <- reactivePoll(4000, session,
# This function returns the time that the logfile was last
# modified
checkFunc = function() {
if (file.exists(logfilename))
file.info(logfilename)$mtime[1]
else
""
},
# This function returns the content of the logfile
valueFunc = function() {
readLines(logfilename)
}
)
output$pollText <- renderText({
# Read the text, and make it a consistent number of lines so
# that the output box doesn't grow in height.
text <- pollData()
length(text) <- 14
text[is.na(text)] <- ""
paste(text, collapse = '\n')
})
}
如果仔细查看上面的代码,您会看到以下代码:
# When the client ends the session, suspend the observer and
# remove the log file.
session$onSessionEnded(function() {
logwriter$suspend()
unlink(logfilename)
})
我想在我的闪亮应用程序中调整该代码,以便将我的MySQL服务器与我的闪亮应用程序断开连接。像这样:
session$onSessionEnded(function() {
dbDisconnect(con)
})
我想这样做以确保此警告消息:“无法连接到数据库:连接太多”
是否可以确保为其他用户释放连接? (我的应用程序出现问题,因为有很多用户打开并且没有断开连接,在服务器上没有可用的位置。)