throttleDB.lua

Added by iNTERFACEWARE

Throttle database access by reducing the number of inserts during peak hours

Source Code
local throttleDB = {}
 
local function IsWeekday(Day)
   -- Sunday == 1, Saturday == 7
   return Day ~= 1 or Day ~= 7
end
 
local function IsPeakTime(Hours, Minutes)
   -- assuming peak time is 10:30 am (10:30) to 3:30 pm (15:30)
   return (Hours > 10 and Hours < 15) or
          (Hours == 10 and Minutes >= 30) or
          (Hours == 15 and Minutes <= 30)
end   
 
-- The definition of "peak period" will be dependent on the situation.
-- Thus this code will be unique for each user.
local function IsPeakPeriod()
   local Date = os.date("*t")
 
   local IsWeekdayValue = IsWeekday(Date.wday) -- wday range is (1-7)
   local IsPeakTimeValue = IsPeakTime(Date.hour, Date.min) -- hour range is (0-23)
                                                           -- min range is (0-59)
   if IsWeekdayValue and IsPeakTimeValue
   then
      return true
   else
      return false   
   end    
end 
 
function throttleDB.DoDataMerge(Out, DbType, DbName, User, Pwd)
   -- Using sleep to throttle database updates during peak periods.
   if IsPeakPeriod() then
      util.sleep(100)
   end
 
   if Out then    
      local conn = db.connect{
         api=DbType, 
         name=DbName, 
         user=User, 
         password=Pwd, 
         live=true}
      conn:merge{data=Out, live=true}
   end       
end
 
return throttleDB
Description
Throttle database access by reducing the number of inserts during peak hours