Execute a command inside thread/timer only once but keep thread/timer running?

This is part of the code inside a thread (or it could be a timer, doesn't matter):

timenow := Now;
strtime := FormatDateTime('hh:nn:ss', timenow);
if frmBackup.getmetime = strtime then
begin
  frmBackup.lawl.Position := frmBackup.lawl.Position + 10;
end;

Basically the progress bar is just a test to know how many times it has been executed. So far, I was not able to stop it from executing more than once. I need it to execute once (when getmetime = strtime) then continue the thread/timer without executing the code, only executing it again when the time comes.

Possible?

Thanks!

Answers


Put a boolean flag on frmBackup:

timenow := Now;
strtime := FormatDateTime('hh:nn:ss', timenow);
if (frmBackup.getmetime = strtime) and (not frmBackup.RanOnce) then
begin
  frmBackup.lawl.Position := frmBackup.lawl.Position + 10;
  frmbackup.RanOnce := true;
end;

Also, be careful of trying to compare times with = like that. If your timer fires one second later than the time you're aiming for, for whatever reason, your code will fail. It would be better to use >= or build some margin of error into the comparison. (And use direct TDateTime comparisons instead of string comparisons.)

And one other thing: if you actually are in another thread, (as opposed to a timer running on the same thread,) updating a VCL control will fail in strange ways, because the underlying Windows API stuff has a thread affinity to the main thread of your program. If you're going to do it that way, look at TThread.Synchronize and TThread.Queue and use one or the other for your UI updates.


Need Your Help

Refactoring code - general way to handle it

javascript algorithm language-agnostic refactoring

I have a code which has a start() function that executes every cycle. In it I call a pause() function here and there.

Is there any Delphi XE2 styles gallery?

delphi delphi-xe2 vcl firemonkey vcl-styles

In XE2 there is a new function : 'styles', for VCL(.vsf) and Firemonkey (.styles), and some are provided in C:\Program Files\Embarcadero\RAD Studio\9.0\Redist\styles directory.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.