One way to do this is to create a "db optimization stream" something like this:
type // a record defining database connection TConnectionSettings = record DatabaseName: string; Server: string; Port: Word; UserName: string; Password: string; end; type TDBOptimizationThread = class(TThread) private FConnection: TDatabaseConnection; // your database connection... I don't know what libraries you are using FQuery: TQuery; // your specific db query protected procedure Execute; override; public constructor Create(AConnectionSettings: TConnectionSettings; destructor Destroy; override; end; implementation constructor TDBOptimizationThread.Create(AConnectionSettings: TConnectionSettings; begin inherited Create(True); // create suspended //FreeOnTerminate := True; // if you want it to be freed when you terminate it // create FConnection and FQuery objects // setup FConnection parameters based on AConnectionSettings end; destructor TDBOptimizationThread.Destroy; begin // destroy objects inherited Destroy; end; procedure TDBOptimizationThread.Execute; begin while NOT Terminated do try // check if it time to run query // you can use a private variable of TDateTime type that will hold // last timestamp of when the query ran, etc. if ItsTimeToRunQuery then begin // check if we still have db connectivity if NOT FConnection.Connected then // ouch, try to connect... FConnection.Connect; FQuery.SQL.Text := 'Your optimization query'; FQuery.Execute; // or ExecSQL or whatever the method is based on your db library end; except on E: Exception do begin // log exception, something went wrong!! end; end; end;
It is very important that your db connection is created and destroyed in this thread, otherwise you will have problems ...
So let the db optimization thread begin
... var LConnSettings: TConnectionSettings; // you may want a private TDBOptimizationThread variable rather than // a variable in a method, but I leave that to you LDBOptimizationThread: TDBOptimizationThread; begin LConnSettings.Database := 'MyDatabase'; LConnSettings.Port := 1234; LConnSettings.Server := 'localhost'; // continue with connection settings... LDBOptimizationThread := TDBOptimizationThread.Create(LConnSettings); LDBOptimizationThread.Start; // start it end;
Of course, you can make it a low priority, but if your requests are not executed for more than a few seconds at any given time, I see no reason for this, but do not hesitate to contradict.
ComputerSaysNo
source share