forked from erlware/erlcron
/
ecrn_agent.erl
479 lines (408 loc) · 14.3 KB
/
ecrn_agent.erl
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
%%%-------------------------------------------------------------------
%%% @author Eric Merritt <emerritt@ecdmarket.com>
%%% @doc
%%% Agent for cronish testing
%%% @end
%%%-------------------------------------------------------------------
-module(ecrn_agent).
-behaviour(gen_server).
%% API
-export([start_link/2,
cancel/1,
get_datetime/1,
set_datetime/3,
recalculate/1,
validate/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("erlcron-internal.hrl").
-record(state, {job,
alarm_ref,
referenced_seconds,
seconds_at_reference,
timeout_type,
fast_forward=false}).
-define(MILLISECONDS, 1000).
-define(WAIT_BEFORE_RUN, 2000).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the server with the apropriate job and the appropriate ref
%% @end
%%--------------------------------------------------------------------
-spec start_link(erlcron:job_ref(), erlcron:job()) -> ok.
start_link(JobRef, Job) ->
gen_server:start_link(?MODULE, [JobRef, Job], []).
-spec get_datetime(pid()) -> erlcron:datetime().
get_datetime(Pid) ->
gen_server:call(Pid, get_datetime).
-spec cancel(pid()) -> ok.
cancel(Pid) ->
gen_server:cast(Pid, shutdown).
-spec set_datetime(pid(), erlcron:datetime(), erlcron:datetime()) -> ok.
set_datetime(Pid, DateTime, Actual) ->
gen_server:cast(Pid, {set_datetime, DateTime, Actual}).
-spec recalculate(pid()) -> ok.
recalculate(Pid) ->
gen_server:cast(Pid, recalculate).
%%--------------------------------------------------------------------
%% @doc
%% Validate that a run_when spec specified is correct.
%% @end
%%--------------------------------------------------------------------
-spec validate(erlcron:run_when()) -> valid | invalid.
validate(Spec) ->
State = #state{job=undefined,
alarm_ref=undefined},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
try
until_next_time(NewState, {Spec, undefined}),
valid
catch
_Error:_Reason ->
erlang:display(erlang:get_stacktrace()),
invalid
end.
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Initiates the server
%%
%% @spec init(Args) -> {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% @end
%%--------------------------------------------------------------------
init([JobRef, Job]) ->
State = #state{job=Job,
alarm_ref=JobRef},
{DateTime, Actual} = ecrn_control:datetime(),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, Job) of
{ok, Millis} when is_integer(Millis) ->
ecrn_reg:register(JobRef, self()),
{ok, NewState, Millis};
{error, _} ->
{stop, normal}
end.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling call messages
%%
%% @spec handle_call(Request, From, State) ->
%% {reply, Reply, State} |
%% {reply, Reply, State, Timeout} |
%% {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_call(_Msg, _From, State) ->
case until_next_milliseconds(State, State#state.job) of
{ok, Millis} ->
{reply, ok, State, Millis};
{error, _} ->
{stop, normal, ok, State}
end.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling cast messages
%%
%% @spec handle_cast(Msg, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_cast(shutdown, State) ->
{stop, normal, State};
handle_cast({set_datetime, DateTime, Actual}, State) ->
fast_forward(State#state{fast_forward=true}, DateTime),
NewState = set_internal_time(State, DateTime, Actual),
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Handling all non call/cast messages
%%
%% @spec handle_info(Info, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_info(timeout, State = #state{job = {{once, _}, _}}) ->
do_job_run(State, State#state.job),
{stop, normal, State};
handle_info(timeout, State = #state{timeout_type=wait_before_run}) ->
NewState = State#state{timeout_type=normal},
case until_next_milliseconds(NewState, NewState#state.job) of
{ok, Millis} ->
{noreply, NewState, Millis};
{error, _} ->
{stop, normal, NewState}
end;
handle_info(timeout, State = #state{job = Job}) ->
do_job_run(State, Job),
NewState = State#state{timeout_type=wait_before_run},
{noreply, NewState, ?WAIT_BEFORE_RUN}.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
%%
%% @spec terminate(Reason, State) -> void()
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, #state{alarm_ref=Ref}) ->
ecrn_reg:unregister(Ref),
ok.
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Convert process state when code is changed
%%
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) ->
RunFun = fun() ->
Job(State#state.alarm_ref, current_date(State))
end,
proc_lib:spawn(RunFun);
do_job_run(State, {_, {M, F, A}}) when is_record(State, state) ->
proc_lib:spawn(M, F, A).
%% @doc Returns the current time, in seconds past midnight.
-spec current_time(record(state)) -> erlcron:seconds().
current_time(State) ->
{_, {H,M,S}} = current_date(State),
S + M * 60 + H * 3600.
current_date(State = #state{fast_forward=true}) ->
calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds);
current_date(State) ->
Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference,
calendar:gregorian_seconds_to_datetime(ceiling(Elapsed +
State#state.referenced_seconds)).
%% @doc Calculates the duration in milliseconds until the next time
%% a job is to be run.
-spec until_next_milliseconds(record(state), erlcron:job()) -> erlcron:seconds().
until_next_milliseconds(State, Job) ->
try
Millis = until_next_time(State, Job) * ?MILLISECONDS,
{ok, Millis}
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.
normalize_seconds(State, Seconds) ->
case Seconds - current_time(State) of
Value when Value >= 0 ->
Value;
_ ->
erlang:display(erlang:get_stacktrace()),
throw(invalid_once_exception)
end.
%% @doc Calculates the duration in seconds until the next time
%% a job is to be run.
-spec until_next_time(record(state), erlcron:job()) -> erlcron:seconds().
until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) ->
Seconds;
until_next_time(State, {{once, {H, M, S}}, _What})
when is_integer(H), is_integer(M), is_integer(S) ->
normalize_seconds(State, S + (M + (H * 60)) * 60);
until_next_time(State, {{once, Period}, _What}) ->
normalize_seconds(State, resolve_time(Period));
until_next_time(State, {{daily, Period}, _What}) ->
until_next_daytime(State, Period);
until_next_time(State, {{weekly, DoW, Period}, _What}) ->
OnDay = resolve_dow(DoW),
{Date, _} = current_date(State),
Today = calendar:day_of_the_week(Date),
case Today of
OnDay ->
until_next_daytime_or_days_from_now(State, Period, 7);
Today when Today < OnDay ->
until_days_from_now(State, Period, OnDay - Today);
Today when Today > OnDay ->
until_days_from_now(State, Period, (OnDay+7) - Today)
end;
until_next_time(State, {{monthly, DoM, Period}, _What}) ->
{{ThisYear, ThisMonth, Today}, _} = current_date(State),
{NextYear, NextMonth} =
case ThisMonth of
12 ->
{ThisYear + 1, 1};
_ ->
{ThisYear, ThisMonth + 1}
end,
D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today),
D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM),
Days = D2 - D1,
case Today of
DoM ->
until_next_daytime_or_days_from_now(State, Period, Days);
_ ->
until_days_from_now(State, Period, Days)
end.
%% @doc Calculates the duration in seconds until the next time this
%% period is to occur during the day.
%% @spec until_next_daytime(period()) -> seconds()
until_next_daytime(State, Period) ->
StartTime = first_time(Period),
EndTime = last_time(Period),
case current_time(State) of
T when T > EndTime ->
until_tomorrow(State, StartTime);
T ->
next_time(Period, T) - T
end.
%% @spec last_time(period()) -> seconds()
%% @doc Calculates the last time in a given period.
last_time(Period) ->
hd(lists:reverse(lists:sort(resolve_period(Period)))).
%% @spec first_time(period()) -> seconds()
%% @doc Calculates the first time in a given period.
first_time(Period) ->
hd(lists:sort(resolve_period(Period))).
%% @spec next_time(period(), seconds()) -> seconds()
%% @doc Calculates the first time in the given period after the given time.
next_time(Period, Time) ->
R = lists:sort(resolve_period(Period)),
lists:foldl(fun(X, A) ->
case X of
T when T >= Time, T < A ->
T;
_ ->
A
end
end, 24*3600, R).
%% @spec resolve_period(period()) -> [seconds()]
%% @doc Returns a list of times given a periodic specification.
resolve_period([]) ->
[];
resolve_period([H | T]) ->
resolve_period(H) ++ resolve_period(T);
resolve_period({every, Duration, {between, TimeA, TimeB}}) ->
Period = resolve_dur(Duration),
StartTime = resolve_time(TimeA),
EndTime = resolve_time(TimeB),
resolve_period0(Period, StartTime, EndTime, []);
resolve_period(Time) ->
[resolve_time(Time)].
resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime ->
Acc;
resolve_period0(Period, Time, EndTime, Acc) ->
resolve_period0(Period, Time + Period, EndTime, [Time | Acc]).
%% @spec resolve_time(time()) -> seconds()
%% @doc Returns seconds past midnight for a given time.
resolve_time({H, M, S}) when H < 24, M < 60, S < 60 ->
S + M * 60 + H * 3600;
resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60 + S;
resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) ->
resolve_time({H, X}) + M * 60;
resolve_time({12, am}) ->
0;
resolve_time({H, am}) when H < 12 ->
H * 3600;
resolve_time({12, pm}) ->
12 * 3600;
resolve_time({H, pm}) when H < 12->
(H + 12) * 3600.
%% @spec resolve_dur(duration()) -> seconds()
%% @doc Returns seconds for a given duration.
resolve_dur({Hour, hr}) ->
Hour * 3600;
resolve_dur({Min, min}) ->
Min * 60;
resolve_dur({Sec, sec}) ->
Sec.
%% @spec resolve_dow(dow()) -> integer()
%% @doc Returns the number of the given day of the week. See the calendar
%% module for day numbers.
resolve_dow(mon) ->
1;
resolve_dow(tue) ->
2;
resolve_dow(wed) ->
3;
resolve_dow(thu) ->
4;
resolve_dow(fri) ->
5;
resolve_dow(sat) ->
6;
resolve_dow(sun) ->
7.
%% @spec until_tomorrow(seconds()) -> seconds()
%% @doc Calculates the duration in seconds until the given time occurs
%% tomorrow.
until_tomorrow(State, StartTime) ->
(StartTime + 24*3600) - current_time(State).
%% @spec until_days_from_now(period(), integer()) -> seconds()
%% @doc Calculates the duration in seconds until the given period
%% occurs several days from now.
until_days_from_now(State, Period, Days) ->
Days * 24 * 3600 + until_next_daytime(State, Period).
%% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds()
%% @doc Calculates the duration in seconds until the given period
%% occurs, which may be today or several days from now.
until_next_daytime_or_days_from_now(State, Period, Days) ->
CurrentTime = current_time(State),
case last_time(Period) of
T when T < CurrentTime ->
until_days_from_now(State, Period, Days-1);
_ ->
until_next_daytime(State, Period)
end.
set_internal_time(State, RefDate, CurrentSeconds) ->
NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate),
State#state{referenced_seconds=NewSeconds,
seconds_at_reference=CurrentSeconds}.
ceiling(X) ->
T = erlang:trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
fast_forward(State, NewDate) ->
try
Seconds = until_next_time(State, State#state.job),
NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate),
Span = NewSeconds - State#state.referenced_seconds,
case Span > Seconds of
true ->
RefSecs = State#state.referenced_seconds,
NewState = State#state{referenced_seconds = RefSecs + Seconds + 2},
do_job_run(State, State#state.job),
fast_forward(NewState, NewDate);
false ->
ok
end
catch
throw:invalid_once_exception ->
{error, invalid_once_exception}
end.