forked from alexdemers/csharp-resque
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorker.cs
268 lines (227 loc) · 7.23 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Resque.Jobs;
namespace Resque
{
public class Worker
{
public enum LogType
{
None, Normal, Verbose
}
public LogType LogLevel = LogType.Verbose;
private readonly string[] _queues;
private bool _shutDown;
private bool _paused;
private Job _currentJob;
public string Id { get; set; }
public Worker(string[] queues)
{
_queues = queues;
Id = string.Format("{0}:{1}:{2}", Dns.GetHostName(), System.Diagnostics.Process.GetCurrentProcess().Id, String.Join(",", _queues));
}
public Worker(string queue)
{
_queues = queue == "*" ? Resque.Queues().ToArray() : new[] { queue };
Id = string.Format("{0}:{1}:{2}", Dns.GetHostName(), System.Diagnostics.Process.GetCurrentProcess().Id, String.Join(",", _queues));
}
public void Work(int interval)
{
try
{
Startup();
var threads = new List<Thread>();
while (true)
{
if (_shutDown)
{
break;
}
var jobs = new List<Job>();
if (!_paused)
{
Job job;
do
{
job = Reserve();
if (job != null)
{
jobs.Add(job);
}
} while (job != null);
}
if (jobs.Count == 0)
{
if (interval == 0) break;
Log("Sleeping for " + interval * 1000);
Thread.Sleep(interval * 1000);
continue;
}
foreach (var job in jobs)
{
var job1 = job;
ThreadStart threadStart = delegate
{
Log("Got " + job1.Queue);
WorkingOn(job1);
Perform(job1);
};
var thread = new Thread(threadStart);
threads.Add(thread);
thread.Start();
}
foreach (var thread in threads)
{
thread.Join();
}
DoneWorking();
}
}
finally
{
UnregisterWorker();
}
}
public void Perform(Job job)
{
try
{
job.Perform();
}
catch (Exception e)
{
Log(job + " failed: " + e.Message);
job.Fail(e);
return;
}
job.UpdateStatus(Status.StatusComplete);
Log("Done " + job);
}
public Job Reserve()
{
foreach (var queue in _queues)
{
Log("Checking " + queue);
var job = global::Resque.Job.Reserve(queue);
if (job == null) continue;
Log("Found job on " + queue);
return job;
}
return null;
}
public string[] Queues(bool fetch = false)
{
if (_queues.Contains("*") || !fetch)
{
return _queues;
}
var queues = Resque.Queues().ToArray();
Array.Sort(queues);
return queues;
}
private void Startup()
{
RegisterWorker();
}
public void PauseProcessing()
{
_paused = true;
Log("Pausing job processing.");
}
public void ResumeProcessing()
{
_paused = true;
Log("Resuming job processing.");
}
public void Shutdown()
{
_shutDown = true;
Log("Exiting…");
}
private void RegisterWorker()
{
using (var redis = Resque.PooledRedisClientManager.GetClient())
{
redis.AddItemToSet("resque:workers", ToString());
redis.Set("resque:worker:" + ToString() + ":started", CurrentTimeFormatted());
}
}
public void UnregisterWorker()
{
if (_currentJob != null)
{
_currentJob.Fail(new DirtyExitException());
}
using (var redis = Resque.PooledRedisClientManager.GetClient())
{
redis.RemoveItemFromSet("resque:workers", Id);
redis.Remove("resque:worker:" + Id);
redis.Remove("resque:worker:" + Id + ":started");
}
Stat.Clear("processed:" + Id);
Stat.Clear("failed:" + Id);
}
public void WorkingOn(Job job)
{
job.Worker = this;
_currentJob = job;
job.UpdateStatus(Status.StatusRunning);
var data = new JObject
{
new JProperty("queue", job.Queue),
new JProperty("run_at", CurrentTimeFormatted()),
new JProperty("payload", job.Payload)
};
using (var redis = Resque.PooledRedisClientManager.GetClient())
{
redis.Set("resque:worker:" + job.Worker, data.ToString());
}
}
public void DoneWorking()
{
_currentJob = null;
Stat.Increment("processed");
Stat.Increment("processed:" + ToString());
using (var redis = Resque.PooledRedisClientManager.GetClient())
{
redis.Remove("resque:worker:" + ToString());
}
}
public override string ToString()
{
return Id;
}
public void Log(string message)
{
switch (LogLevel)
{
case LogType.Normal:
Console.WriteLine("*** " + message);
break;
case LogType.Verbose:
Console.WriteLine(string.Format("[{0}] {1}", new DateTime().ToString(), message));
break;
}
}
public JObject Job()
{
using (var redis = Resque.PooledRedisClientManager.GetClient())
{
return JsonConvert.DeserializeObject<JObject>(redis.GetValue("resque:worker:" + Id));
}
}
public int GetStat(string stat)
{
return Stat.Get(stat + ":" + ToString());
}
private static string CurrentTimeFormatted()
{
return DateTime.Now.ToString("ddd MMM dd hh:mm:ss zzzz yyyy");
}
}
}