throttleDB.lua

Verified
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
Usage Details

The process for the throttleDB module is quite simple: It finds the current time, and checks to see if it falls within the specified peak time. If it does, then database access is throttled, by waiting for 100 milliseconds between inserts.

How to use throttleDB.lua:

  • Add it to your shared modules in any Translator project
  • Add local throttled = require 'throttleDB' at the top of your script
  • Use throttled.DoDataMerge() to merge data to the database

Here is some example code for main():

local throttled = require 'throttleDB'

function main(Data)
   local T = MapData(Data)
   if T then
      throttled.DoDataMerge(T, db.SQL_SERVER, 'Test', '', '')
   end
end

function MapData(Data)
   local Msg, Name = hl7.parse{vmd='demo.vmd', data=Data}
   local Out = db.tables{vmd='demo.vmd', name=Name}

   -- Map data from Msg to Out here

   return Out
end