Commit 4aa19f61 authored by Charles's avatar Charles

add mysql failover case

parent 8a9822cf
library(data.table)
library(RMySQL)
library(mailR)
con <- dbConnect(MySQL(),
user = Sys.getenv("VELOV_USER"),
......@@ -50,10 +51,46 @@ dispo_url <- paste0("https://download.data.grandlyon.com/ws/rdata/",
dt <- jsonlite::fromJSON(dispo_url)$values
dt <- data.table(dt)
dbWriteTable(con, "dispo", dt, append = TRUE)
res <- tryCatch(dbWriteTable(con, "dispo", dt, append = TRUE),
error = function(e) FALSE,
warning = function(e) FALSE)
# If writing fails, attempt again in 5 minutes
for (i in 1:300) {
if (res == FALSE) {
Sys.sleep(5 * 60)
res <- tryCatch(dbWriteTable(con, "dispo", dt, append = TRUE),
error = function(e) FALSE,
warning = function(e) FALSE)
}
}
# If still fails, send an email and save data in csv
if (res == FALSE) {
send.mail(from = "charles@datachamp.fr",
to = "charles@datachamp.fr",
subject = "Failure writing to velov database",
body = "The database has been offline for 24 hours.",
encoding = "utf-8",
smtp = list(host.name = "in-v3.mailjet.com",
port = 25,
user.name = Sys.getenv("MAILJET_API_KEY"),
passwd = Sys.getenv("MAILJET_API_SECRET")),
authenticate = TRUE,
debug = FALSE)
fwrite(dt, file = file.path(Sys.getenv("VELOV_CSV"), "data",
paste0(as.integer(Sys.time()), ".csv")))
}
dbDisconnect(con)
if (res == TRUE) {
dt <- data.table(time = Sys.time(),
success = TRUE)
fwrite(dt, file = file.path(Sys.getenv("VELOV_CSV"), "logs.csv"),
append = TRUE)
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment