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.
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.