source: trunk/Packages/Kernel/Kernel.Scheduler.pas

Last change on this file was 60, checked in by chronos, 8 months ago
  • Modified: Remove U prefix from unit names.
File size: 2.4 KB
Line 
1unit Kernel.Scheduler;
2
3interface
4
5uses
6 Classes, SysUtils, Kernel.List, Kernel.Classes;
7
8type
9 TTask = class;
10 TScheduler = class;
11
12 TTaskEvent = procedure(Task: TTask) of object;
13
14 TTaskState = (tsStopped, tsRunning, tsSuspended, tsWaiting);
15
16 TWaitReason = (wrSleep, wrMessage);
17
18 { TTask }
19
20 TTask = class(TNamedObject)
21 Scheduler: TScheduler;
22 State: TTaskState;
23 WaitReason: TWaitReason;
24 WakeUpTime: TDateTime;
25 Terminated: Boolean;
26 EntryPoint: TTaskEvent;
27 Messages: TObjectQueue; // TQueue<TIPMessage>
28 procedure WaitForMessage;
29 procedure Sleep(Duration: TDateTime);
30 constructor Create; virtual;
31 destructor Destroy; override;
32 end;
33
34 TTaskClass = class of TTask;
35
36 { TScheduler }
37
38 TScheduler = class
39 TaskClass: TTaskClass;
40 Tasks: TNamedObjects<TTask>;
41 Running: Boolean;
42 function GetCurrentTask: TTask; virtual;
43 procedure Start; virtual;
44 procedure Stop; virtual;
45 function AddTask(Name: string; EntryPoint: TTaskEvent): TTask; virtual;
46 procedure SwitchNext; virtual;
47 constructor Create; virtual;
48 destructor Destroy; override;
49 end;
50
51 TSchedulerClass = class of TScheduler;
52
53
54implementation
55
56{ TTask }
57
58procedure TTask.WaitForMessage;
59begin
60 WaitReason := wrMessage;
61 State := tsWaiting;
62 Scheduler.SwitchNext;
63end;
64
65procedure TTask.Sleep(Duration: TDateTime);
66begin
67 WakeUpTime := Now + Duration;
68 State := tsWaiting;
69 WaitReason := wrSleep;
70 Scheduler.SwitchNext;
71end;
72
73constructor TTask.Create;
74begin
75 Messages := TObjectQueue.Create;
76end;
77
78destructor TTask.Destroy;
79begin
80 FreeAndNil(Messages);
81 inherited;
82end;
83
84{ TScheduler }
85
86function TScheduler.GetCurrentTask: TTask;
87begin
88 Result := nil;
89end;
90
91procedure TScheduler.Start;
92begin
93 Running := True;
94end;
95
96procedure TScheduler.Stop;
97begin
98 Running := False;
99end;
100
101function TScheduler.AddTask(Name: string; EntryPoint: TTaskEvent): TTask;
102var
103 NewTask: TTask;
104begin
105 NewTask := TaskClass.Create;
106 NewTask.Scheduler := Self;
107 NewTask.Name := Name;
108 NewTask.EntryPoint := EntryPoint;
109 Tasks.Add(NewTask);
110 Result := NewTask;
111end;
112
113procedure TScheduler.SwitchNext;
114begin
115
116end;
117
118constructor TScheduler.Create;
119begin
120 TaskClass := TTask;
121 Tasks := TNamedObjects<TTask>.Create;
122end;
123
124destructor TScheduler.Destroy;
125begin
126 if Running then Stop;
127 Tasks.Free;
128 inherited Destroy;
129end;
130
131
132end.
133
Note: See TracBrowser for help on using the repository browser.