@@ -13,19 +13,57 @@ const BitSet = std.bit_set.IntegerBitSet(130);
13
13
14
14
const LEN = 48 ;
15
15
16
+ /// A sturct for parsing cron strings and calculating next and previous execution datetimes.
17
+ /// Example:
18
+ /// ```zig
19
+ /// const std = @import("std");
20
+ /// const Cron = @import("cron").Cron;
21
+ /// const datetime = @import("datetime").datetime;
22
+ ///
23
+ /// fn job1(i: usize) !void {
24
+ /// const now = datetime.Datetime.now();
25
+ ///
26
+ /// var buf: [64]u8 = undefined;
27
+ /// const dt_str = try now.formatISO8601Buf(&buf, false);
28
+ /// std.log.info("{s} {d}th execution", .{ dt_str, i });
29
+ /// }
30
+ ///
31
+ /// pub fn main() !void {
32
+ /// var c = Cron.init();
33
+ /// // At every minute.
34
+ /// try c.parse("*/1 * * * *");
35
+ ///
36
+ /// for (0..5) |i| {
37
+ /// const now = datetime.Datetime.now();
38
+ ///
39
+ /// // Get the next run time
40
+ /// const next_dt = try c.next(now);
41
+ /// const duration = next_dt.sub(now);
42
+ /// // convert to nanoseconds
43
+ /// const nanos = duration.totalSeconds() * std.time.ns_per_s + duration.nanoseconds;
44
+ ///
45
+ /// // wait next
46
+ /// std.time.sleep(@intCast(nanos));
47
+ ///
48
+ /// try job1(i + 1);
49
+ /// }
50
+ /// }
51
+ /// ```
16
52
pub const Cron = struct {
17
53
buf : [LEN ]u8 ,
18
54
expr : CronExpr ,
19
55
20
56
const Self = @This ();
21
57
58
+ /// Initialize cron
22
59
pub fn init () Self {
23
60
return Self {
24
61
.buf = undefined ,
25
62
.expr = undefined ,
26
63
};
27
64
}
28
65
66
+ /// Parse cron expression
29
67
pub fn parse (self : * Self , input : []const u8 ) ! void {
30
68
var buf_ : [LEN ]u8 = undefined ;
31
69
const lower_input = std .ascii .lowerString (& buf_ , input );
@@ -156,6 +194,7 @@ pub const Cron = struct {
156
194
unreachable ;
157
195
}
158
196
197
+ /// Calculates and returns the datetime of the next scheduled execution based on the parsed cron schedule and the provided starting datetime.
159
198
pub fn next (self : * Self , now : datetime.Datetime ) ! datetime.Datetime {
160
199
// reset nanoseconds
161
200
var future = now .shift (.{ .nanoseconds = - @as (i32 , @intCast (now .time .nanosecond )) }).shiftSeconds (1 );
@@ -221,6 +260,7 @@ pub const Cron = struct {
221
260
return future ;
222
261
}
223
262
263
+ /// Calculates and returns the datetime of the most recent past scheduled execution based on the parsed cron schedule and the provided starting datetime.
224
264
pub fn previous (self : * Self , now : datetime.Datetime ) ! datetime.Datetime {
225
265
// reset nanoseconds
226
266
var future = now .shift (.{ .nanoseconds = - @as (i32 , @intCast (now .time .nanosecond )) }).shiftSeconds (-1 );
0 commit comments