Locking files for better parallel sync
padlock <- function(dir,fun,id) {
if( missing(id) ) { id <- NULL }
if( missing(dir) ) { dir <- NULL }
if( missing(fun) ) { fun <- NULL }
options(warn=-1)
file.t <- paste0("Padlocker#",id,".Lk")
## ---------------------------
if( fun == "Lock" ) {
write("Locked",file=paste0(dir,"/",file.t),append=FALSE)
}
## ---------------------------
if( fun == "Unlock" ) {
file.remove( paste0(dir,"/",file.t) )
if( id == -1 ) {
file.remove( list.files(dir,"Padlocker#",full.names = TRUE) )
}
}
## ---------------------------
if( fun == "isLocked" ) {
Locked <- TRUE
fs <- list.files(dir,"Padlocker#",full.names = TRUE)
if( length(fs) != 0 ) {
Locked <- TRUE
}
if( length(fs) == 0 ) {
Locked <- FALSE
}
return( Locked )
}
## ---------------------------
if( fun == "uniqueLocker" ) {
u.locker <- FALSE
fs <- list.files(dir,"Padlocker#",full.names = TRUE)
if( length(fs) == 0) { u.locker <- FALSE }
if( length(fs) > 1) { u.locker <- FALSE }
if( length(fs) == 1 ) {
if( grepl(file.t,fs) ) { u.locker <- TRUE }
}
return( u.locker )
}
## ---------------------------
if( fun == "countLockers" ) {
fs <- list.files(dir,"Padlocker#",full.names = TRUE)
return( length(fs) )
}
## ---------------------------
if( fun == "Age" ) {
fs <- list.files(dir,"Padlocker#",full.names = TRUE)
age.i <- numeric(0)
if( length(fs) > 0 ) {
for( i in 1:length(fs)) {
age <- as.numeric( difftime(Sys.time(), file.info(fs[i] )$atime, units ="mins") )
age.i <- c(age.i,age)
}
}
if( length(fs) == 0 ) {
age.i <- 0
}
return(min(age.i))
}
## ---------------------------
options(warn=0)
}