随笔 - 2146  文章 - 19 评论 - 11846 阅读 - 1267万

unit WTimer;

interface

uses
  Windows, SysUtils, SyncObjs;

type
  TWaitableTimer = class(TSynchroObject)
  protected
    FHandle: THandle;
    FPeriod: LongInt;
    FDueTime: TDateTime;
    FLastError: Integer;
    FLongTime: Int64;
  public
    constructor Create(ManualReset : Boolean;
      TimerAttributes: PSecurityAttributes; const Name : string );
    destructor Destroy; override;
    procedure Start;
    procedure Stop;
    function Wait(Timeout: LongInt): TWaitResult;
    property Handle: THandle read FHandle;
    property LastError: integer read FLastError;
    property Period: integer read FPeriod write FPeriod;
    property Time: TDateTime read FDueTime write FDueTime;
    property LongTime: int64 read FLongTime write FLongTime;
  end;

implementation

{ TWaitableTimer }
constructor TWaitableTimer.Create(ManualReset: Boolean;
  TimerAttributes: PSecurityAttributes; const Name: string);
var
  pName: PChar;
begin
 inherited Create;
 if Name = '' then pName := nil else pName := PChar(Name);
 FHandle := CreateWaitableTimer(TimerAttributes, ManualReset, pName);
end;

destructor TWaitableTimer.Destroy;
begin
  CloseHandle(FHandle);
  inherited Destroy;
end;

procedure TWaitableTimer.Start;
var
  SysTime: TSystemTime;
  LocalTime, UTCTime: FileTime;
  Value: Int64 absolute UTCTime;
begin
  if FLongTime = 0 then
  begin
    DateTimeToSystemTime(FDueTime, SysTime);
    SystemTimeToFileTime(SysTime, LocalTime);
    LocalFileTimeToFileTime(LocalTime, UTCTime);
  end else
    Value := FLongTime;
  SetWaitableTimer(FHandle, Value, FPeriod, nil, nil, False);
end;

procedure TWaitableTimer.Stop;
begin
  CancelWaitableTimer(FHandle);
end;

function TWaitableTimer.Wait(Timeout: Integer): TWaitResult;
begin
  case WaitForSingleObjectEx(Handle, Timeout, BOOL(1)) of
    WAIT_ABANDONED: Result := wrAbandoned;
    WAIT_OBJECT_0: Result := wrSignaled;
    WAIT_TIMEOUT: Result := wrTimeout;
    WAIT_FAILED: begin
      Result := wrError;
      FLastError := GetLastError;
    end;
  else
    Result := wrError;
  end;
end;

end.

posted on   万一  阅读(4793)  评论(3编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2008-02-19 WinAPI: waveInClose - 关闭指定的波形输入设备
2008-02-19 WinAPI: waveInAddBuffer - 向波形输入设备发送一个输入缓冲区
2008-02-19 动画演示 Delphi 2007 IDE 功能[2] - 定义变量
2008-02-19 颜色转换函数: 从 Delphi 到 Html
2008-02-19 Delphi 中的颜色常量及效果图
2008-02-19 动画演示 Delphi 2007 IDE 功能[1] - 建立工程、添加控件


点击右上角即可分享
微信分享提示