gpt4 book ai didi

multithreading - 如何让delphi等待30秒然后继续

转载 作者:行者123 更新时间:2023-12-03 18:56:22 25 4
gpt4 key购买 nike

我正在尝试进行无限循环,但我希望循环每30秒运行一次。循环将开始。一堆if语句发生,一些信息将被更改。然后,循环必须暂停30秒,然后循环才能再次开始。这必须永远持续下去。

我正在寻找一种方法暂停循环30秒,然后继续。任何好的建议,将不胜感激。

EDIT #1



程序根据日期和时间显示“特殊”信息:随着时间的变化,信息也随之变化:06:00 =数学; 07:30 =生物学。该程序还向您显示直到下一个类开始为止的时间。因此,程序需要连续运行以更新时间,以便它确切地知道它是哪个时间段以及到下一个时间段还剩下多少时间。

EDIT #2



我想放入一个“刷新”脚本,以便在设定的时间间隔内调用该脚本,以使其不会持续运行并占用公羊。此间隔必须为30秒。

最佳答案

如果您有阻止GUI的代码,则可以使用后台线程和事件来提供非阻止计时器。

创建一个新的Forms应用程序,然后在表单上放置一个TMemo组件。
本示例将在您的TMemo中添加带有当前时间的新行。

主要形式:

unit u_frm_main;

interface

uses
u_workthread,
SysUtils,
Windows,
Forms,
SyncObjs, Classes, Controls, StdCtrls;

type
TForm1 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
Worker : TWorkThread;
procedure ShowData;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.ShowData;
begin
// do whatever you need to do here...
// show current time in memo
Memo1.Lines.Add(FormatDateTime('HH:NN:SS', Now));
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
// create our worker thread and start it
Worker := TWorkThread.Create(3, ShowData);
Worker.Start;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
// signal our worker thread that we are done here
Worker.ThreadEvent.SetEvent;
// terminate and wait
Worker.Terminate;
Worker.WaitFor;
end;

end.

工作线程:
unit u_workthread;

interface

uses
SysUtils,
SyncObjs,
Classes;

type
TWorkProc = procedure of object;

TWorkThread = class(TThread)
private
{ Private declarations }
Counter : Integer;
FTimeout : Integer;
FEventProc: TWorkProc;
procedure DoWork;
protected
procedure Execute; override;
public
ThreadEvent : TEvent;
constructor Create(TimeoutSeconds : Integer; EventProc: TWorkProc ); // timeout in seconds
destructor Destroy; override;
end;

implementation

procedure TWorkThread.DoWork;
begin
// put your GUI blocking code in here. Make sure you never call GUI elements from this procedure
//DoSomeLongCalculation();
end;

procedure TWorkThread.Execute;
begin
Counter := 0;
while not Terminated do
begin
if ThreadEvent.WaitFor(FTimeout) = wrTimeout then
begin
DoWork;
// now inform our main Thread that we have data
Synchronize(FEventProc);
end;
else
// ThreadEvent has been signaled, exit our loop
Break;
end;
end;

constructor TWorkThread.Create(TimeoutSeconds : Integer; EventProc: TWorkProc);
begin
ThreadEvent := TEvent.Create(nil, True, False, '');
// Convert to milliseconds
FTimeout := TimeoutSeconds * 1000;
FEventProc:= EventProc;
// call inherited constructor with CreateSuspended as True
inherited Create(True);
end;

destructor TWorkThread.Destroy;
begin
ThreadEvent.Free;
inherited;
end;


end.

关于multithreading - 如何让delphi等待30秒然后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com