单例模式用于限制进程中只有一个某个类的对象,本例的Singleton是一个线程实例,在每一个时钟到达时检测是否到达某个时刻(本例的时刻存于Ini文件中),如果到达则产生一个线程,但是如果在这个线程完成其任务前又到达一个时钟,则有可能会产生多个线程执行任务,以致出现混乱,所以考虑使用Singleton模式解决这个问题(当然还有其他解决方案,但本例使用的是Singleton)。
核心代码如下:
| //timer单元 procedure TService1.Timer_mainTimer(Sender: TObject); var mystringlist:TStringList; SearchRec: TSearchRec; nowtime :string; begin try DateTimeToString(nowtime,'hh:nn',now); if LeftStr(nowtime,4)=LeftStr(GetMSG('GAME','下发时间',theexename+'.ini'),4) then begin //创建发送线程 Global_Instance:=TSendThread.getInstance; ////////////// end; except on e: Exception do begin //捕获错误存入txt文件 mystringlist:=TStringList.Create; if FileExists(ExtractFilePath(Paramstr(0))+'Err.txt') then mystringlist.LoadFromFile(ExtractFilePath(Paramstr(0))+'Err.txt'); mystringlist.Add('('+DateTimeToStr(Now)+')[创建线程出错:]'+E.Message); mystringlist.SaveToFile(ExtractFilePath(Paramstr(0))+'Err.txt'); mystringlist.Free; if FindFirst(ExtractFilePath(Paramstr(0))+'Err.txt', faAnyFile, SearchRec)=0 then begin if SearchRec.Size>5000000 then begin RenameFile(ExtractFilePath(Paramstr(0))+'Err.txt',ansireplacestr(ExtractFilePath(Paramstr(0)) +'Err.txt','.txt',FormatDateTime('yyyy-MM-dd hh-mm-ss',now)+'.txt')); end; end; end; end; end; //线程单元 interface type TSendThread = class(TThread) protected var implementation uses DB; class function TSendThread.getInstance:TSendThread; constructor TSendThread.Create(CreateSuspended: Boolean); destructor TSendThread.Destroy; procedure TSendThread.Execute; end. |
相关专题
- 熊猫烧香核心源码(Delphi模仿版-仅供学习 (11349次浏览)
- 用Delphi开发视频聊天软件 (4953次浏览)
- Delphi控制Excel自动生成报表 (4001次浏览)
- 动态语言崛起 Delphi For PHP能否挽救Borla (2976次浏览)
- Delphi 中串口通讯的实现 (2889次浏览)
- 用Delphi + DirectX开发简单RPG游戏 (2551次浏览)
- 用Delphi和Web Services开发短信应用程序 (2043次浏览)
- 使用TCP/IP协议实现聊天程序 (1827次浏览)
- 用DELPHI实现文件加密压缩 (1721次浏览)
- 利用Delphi编程控制摄像头 (1391次浏览)



