I am trying to create a scheduled task that will run an R script that uploads a datafile to dropbox. I read that batch files are useful for this and are easy to use with the Windows Task Scheduler, so I made a batch file following the instructions here. When I run the script in Rstudio it works as expected and the file appears in my dropbox, but when I run the batch file (just by double clicking it, not in the task scheduler yet), a command window opens with the text of the batch file, closes, but the file does not update in Dropbox
Here is the code I am running in R. I suspect that the reason it isn't working may have something to do with the file paths specified in the Rscript, as I don't know what the Rscript.exe recognizes as the working directory.
library(rdrop2)
library(httr)
library(dplyr)
#Set up refreshable access token, can pass this to any 'drop' function in 'dtoken' argument
.dstate <- new.env(parent = emptyenv())
drop_auth_RT <- function (new_user = FALSE, key = "placeholder", secret = "placeholder", cache = TRUE, rdstoken = NA)
{
if (new_user == FALSE & !is.na(rdstoken)) {
if (file.exists(rdstoken)) {
.dstate$token <- readRDS(rdstoken)
}
else {
stop("token file not found")
}
}
else {
if (new_user && file.exists(".httr-oauth")) {
message("Removing old credentials...")
file.remove(".httr-oauth")
}
dropbox <- httr::oauth_endpoint(authorize = "https://www.dropbox.com/oauth2/authorize?token_access_type=offline",
access = "https://api.dropbox.com/oauth2/token")
# added "?token_access_type=offline" to the "authorize" parameter so that it can return an access token as well as a refresh token
dropbox_app <- httr::oauth_app("dropbox", key, secret)
dropbox_token <- httr::oauth2.0_token(dropbox, dropbox_app,
cache = cache)
if (!inherits(dropbox_token, "Token2.0")) {
stop("something went wrong, try again")
}
.dstate$token <- dropbox_token
}
}
refreshable_token <- drop_auth_RT()
#upload file
drop_upload(file = "../Learning R/data_original/biostats.csv", path = "/auto_test",
mode = "overwrite",
dtoken = refreshable_token)
most of the code here is just creating a refreshable token to mitigate the short-lived access token with the Dropbox API, the last line is the important one (I think). My working directory in Rstudio is set to the .R file location
and here is the batch file I am trying to run:
@ECHO ON
"C:\Program Files\R\R-4.2.2\bin\Rscript.exe" CMD BATCH "C:\Users\benke\Documents\R Main Directory\Data Upload Automation\Initial_test.R"
EDIT: It also may have to do with the DropBox API. There is an .httr-oauth file and a .gitignore file that are created in the same directory as the script when I run the file, but I don't see why that would matter if the R script is run succesfully since it should just create those files again (?)