循环执行的定时器多线程框架

本文介绍了一个使用Delphi编写的循环执行的定时器多线程框架,该框架允许设置间隔并支持快速终止线程。通过创建TIntervalThread类实例,设置间隔,然后启动线程,可以实现在后台执行周期任务。线程结束时,需调用SetOver方法确保定时器被正确关闭。
摘要由CSDN通过智能技术生成


  2008.02.26 coded by cqwty
  email:cqwty@sina.com
}

2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078
unit IntervalThreadUnit;

interface

uses
  Classes, mmsystem, Windows, sysutils, Forms, FileCtrl;

type
  TIntervalThread = class(TThread)
  private
    { Private declarations }
    fInterval: Integer;
    timerid:integer;
    htimerevent:Thandle;
    procedure SetInterval(Value: Integer);
  protected
    procedure Execute; override;
  public
    constructor create;
    procedure SetOver;
  published
    property Interval:Integer read fInterval write SetInterval;
  end;

implementation

constructor TIntervalThread.Create;
begin
  FreeOnTerminate := true;
  Inherited Create(true);
end;

procedure TIntervalThread.SetOver;
begin
  timerid := timesetevent(5,0,TFNTimecallback(htimerevent),0,time_periodic or time_callback_event_set);
end;

procedure TIntervalThread.SetInterval(Value: Integer);
begin
  if Interval <> Value then
    fInterval := Value;
end;

procedure TIntervalThread.Execute;
begin
  htimerevent := CreateEvent(nil, False, False, nil);
  timerid := timesetevent(FInterval*1000,0,TFNTimecallback(htimerevent),0,time_periodic or time_callback_event_set);
  repeat
    if WaitForSingleObject(htimerevent,INFINITE) = WAIT_OBJECT_0 then
    begin
      if Terminated then break;
      DoSomething;
    end;
  until false;
  timekillevent(timerid);
  CloseHandle(htimerevent);
end;

end.

调用的时候需要先创建,然后对该线程的属性赋值,最后在resume即可了。
要结束线程的时候,先调用setover,然后在调用线程自身的terminate即可。
保证了能最快的速度结束正在定时循环执行的多线程。
如有任何建议或者意见,请mail我。谢谢。  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值