2015-10-20 104 views
3

我试图跟踪用户活动,因为他们通过我的闪亮应用程序。我将函数放置在将行写入临时文件的特定位置。我想要的是在用户会话结束时调用一个函数。

根据文档:

> ?session 
> onSessionEnded(callback) 
     Registers a function to be called after the client has disconnected. Returns a function that can be called with no arguments to cancel the registration. 

我试图用这样的:

session$onSessionEnded(function(x){ 
    a = read_csv(shinyActivityTmpFile_000) 
    write_csv(a,'C:\\Users\\xxxx\\Desktop\\test.csv') 
}) 

但是什么都没有发生。 shinyActivityTmpFile_000是一个全局文件参考。当用户点击按钮并执行某些操作时,该应用程序将以CSV格式写入该文件。我只是试图将其从临时存储转移到永久存储。最终,我希望函数将其写入数据库,但为了测试,我只是试图获得将在应用程序关闭时运行的函数。

我在这里错过了什么?

+0

与功能没有参数尝试在'onSessionEnded':'函数(){...}' – Victorp

回答

10

您好我不知道你是如何构建shinyActivityTmpFile文件,但使用onSessionEnded你可以看看这个为例,它在文件中写的日期时间,当一个应用程序被启动,当应用程序被关闭:

library("shiny") 
ui <- fluidPage(
    "Nothing here" 
) 
server <- function(input, output, session) { 
    # This code will be run once per user 
    users_data <- data.frame(START = Sys.time()) 

    # This code will be run after the client has disconnected 
    session$onSessionEnded(function() { 
    users_data$END <- Sys.time() 
    # Write a file in your working directory 
    write.table(x = users_data, file = file.path(getwd(), "users_data.txt"), 
       append = TRUE, row.names = FALSE, col.names = FALSE, sep = "\t") 
    }) 
} 
shinyApp(ui = ui, server = server) 

如果您使用的身份验证的服务器,你可以检索与用户名:

users_data <- data.frame(USERS = session$user, START = Sys.time()) 
+0

有任何方式来指定只有一个会话做某事g当会话结束时。例如 'session $ onSessionEnded(function(){ if(userID == 1)cat(“Do Something Wild”)})' – Jordan