Beto Neto
Beto Neto

Reputation: 4112

Synchronizing local time with databaser server time

I have to synchronize my local date and time with the same date and time returned from the database.

The sql:

select first 1 CURRENT_TIMESTAMP from RDB$DATABASE

This SQL command returns the current date and time at the database server.

Now, I need to cache this and provide the correct time based on the local diff. The problem is that the local date and time can be changed again.

How can I do this to garantee the correct date time without execute the SQL again?


I found a solution:

var
  SQLTimestamp: TDateTime=0;
  LocalTimestamp: TDateTime=0;

function SysUpTime : TDateTime;
var
  Count, Freq : int64;
begin
  QueryPerformanceCounter(count);
  QueryPerformanceFrequency(Freq);
  if (count<> 0) and (Freq <> 0) then
  begin
    Result := Count / Freq;
    Result := result / SecsPerDay;
  end
  else
    Result := 0;
end;

function RealTime: TDateTime;
var
  queryTime, dbTime: tdatetime;
begin
  if SQLTimestamp = 0 then
  begin
    queryTime := SysUpTime;
    dbTime := // SQL QUERY EXECUTION
    queryTime := SysUpTime - queryTime;

    LocalTimestamp := SysUpTime;
    SQLTimestamp := dbTime + queryTime;
  end;

  Result := SQLTimestamp + (SysUpTime - LocalTimestamp);
end;

Now my question is: QueryPerformanceCounter and QueryPerformanceFrequency has the same limitation as GetTickCount?

 The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days. 

Upvotes: 0

Views: 2297

Answers (1)

Arioch &#39;The
Arioch &#39;The

Reputation: 16065

What does any cache do ? It gives you a ready-made result if some defining conditions still hold, or re-query/re-calculate result if they changed.

That is what you cache have to do as well. Just re-execute the query if the local time was overrode and use the cache while it is continuous.

Do re-execute the query, just do it only when you need it rather than on every attempt. http://msdn.microsoft.com/ru-ru/library/windows/desktop/ms725498.aspx

Now what i'd really like to know what would you do if the server's clock would be changed, not the local one. Maybe you'd really install separate time-syncing service along wit hdatabase server?

Upvotes: 1

Related Questions