easy-schedule 0.11.3

A flexible task scheduler built on Tokio with multiple scheduling options and skip conditions
Documentation
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use async_trait::async_trait;
use std::fmt::Debug;
use time::{Date, OffsetDateTime, Time, UtcOffset, macros::format_description};
use tokio_util::sync::CancellationToken;

/// a task that can be scheduled
#[async_trait]
pub trait Notifiable: Sync + Send + Debug {
    /// get the schedule type
    fn get_task(&self) -> Task;

    /// called when the task is scheduled
    ///
    /// Default cancel on first trigger
    async fn on_time(&self, cancel: CancellationToken) {
        cancel.cancel();
    }

    /// called when the task is skipped
    async fn on_skip(&self, _cancel: CancellationToken) {
        // do nothing
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Skip {
    /// skip fixed date
    Date(Date),
    /// skip date range
    DateRange(Date, Date),
    /// skip days
    ///
    /// 1: Monday, 2: Tuesday, 3: Wednesday, 4: Thursday, 5: Friday, 6: Saturday, 7: Sunday
    Day(Vec<u8>),
    /// skip days range
    ///
    /// 1: Monday, 2: Tuesday, 3: Wednesday, 4: Thursday, 5: Friday, 6: Saturday, 7: Sunday
    DayRange(usize, usize),
    /// skip fixed time
    Time(Time),
    /// skip time range
    ///
    /// end must be greater than start
    TimeRange(Time, Time),
    /// no skip
    None,
}

impl Default for Skip {
    fn default() -> Self {
        Self::None
    }
}

impl std::fmt::Display for Skip {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Skip::Date(date) => write!(f, "date: {date}"),
            Skip::DateRange(start, end) => write!(f, "date range: {start} - {end}"),
            Skip::Day(day) => write!(f, "day: {day:?}"),
            Skip::DayRange(start, end) => write!(f, "day range: {start} - {end}"),
            Skip::Time(time) => write!(f, "time: {time}"),
            Skip::TimeRange(start, end) => write!(f, "time range: {start} - {end}"),
            Skip::None => write!(f, "none"),
        }
    }
}

impl Skip {
    /// check if the time is skipped
    pub fn is_skip(&self, time: OffsetDateTime) -> bool {
        match self {
            Skip::Date(date) => time.date() == *date,
            Skip::DateRange(start, end) => time.date() >= *start && time.date() <= *end,
            Skip::Day(day) => day.contains(&(time.weekday().number_from_monday())),
            Skip::DayRange(start, end) => {
                let weekday = time.weekday().number_from_monday() as usize;
                weekday >= *start && weekday <= *end
            }
            Skip::Time(skip_time) => time.time() == *skip_time,
            Skip::TimeRange(start, end) => {
                let current_time = time.time();
                if start <= end {
                    // 同一天内的时间范围
                    current_time >= *start && current_time <= *end
                } else {
                    // 跨日期的时间范围 (如 22:00 - 06:00)
                    current_time >= *start || current_time <= *end
                }
            }
            Skip::None => false,
        }
    }
}

#[derive(Debug, Clone)]
pub enum Task {
    /// wait seconds
    Wait(u64, Option<Vec<Skip>>),
    /// interval seconds
    Interval(u64, Option<Vec<Skip>>),
    /// at time
    At(Time, Option<Vec<Skip>>),
    /// exact time
    Once(OffsetDateTime, Option<Vec<Skip>>),
}

impl PartialEq for Task {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Task::Wait(a, skip_a), Task::Wait(b, skip_b)) => a == b && skip_a == skip_b,
            (Task::Interval(a, skip_a), Task::Interval(b, skip_b)) => a == b && skip_a == skip_b,
            (Task::At(a, skip_a), Task::At(b, skip_b)) => a == b && skip_a == skip_b,
            (Task::Once(a, skip_a), Task::Once(b, skip_b)) => a == b && skip_a == skip_b,
            _ => false,
        }
    }
}

impl Task {
    /// get the next run time for the scheduled task
    pub fn get_next_run_time<T: Notifiable + 'static>(
        &self,
        timezone_minutes: i16,
    ) -> Option<OffsetDateTime> {
        let now = get_now(timezone_minutes).unwrap_or_else(|_| OffsetDateTime::now_utc());

        match self.clone() {
            Task::Wait(wait, skip) => {
                let mut next_time = now + time::Duration::seconds(wait as i64);

                if let Some(skip_rules) = skip {
                    let mut attempts = 0;
                    const MAX_ATTEMPTS: u32 = 1000;

                    while skip_rules.iter().any(|s| s.is_skip(next_time)) && attempts < MAX_ATTEMPTS
                    {
                        next_time += time::Duration::seconds(wait as i64);
                        attempts += 1;
                    }

                    if attempts >= MAX_ATTEMPTS {
                        return None;
                    }
                }

                Some(next_time)
            }
            Task::Interval(interval, skip) => {
                let mut next_time = now + time::Duration::seconds(interval as i64);

                if let Some(skip_rules) = skip {
                    let mut attempts = 0;
                    const MAX_ATTEMPTS: u32 = 1000;

                    while skip_rules.iter().any(|s| s.is_skip(next_time)) && attempts < MAX_ATTEMPTS
                    {
                        next_time += time::Duration::seconds(interval as i64);
                        attempts += 1;
                    }

                    if attempts >= MAX_ATTEMPTS {
                        return None;
                    }
                }

                Some(next_time)
            }
            Task::At(time, skip) => {
                let mut next_time = get_next_time(now, time);

                if let Some(skip_rules) = skip {
                    let mut attempts = 0;
                    const MAX_ATTEMPTS: u32 = 365;

                    while skip_rules.iter().any(|s| s.is_skip(next_time)) && attempts < MAX_ATTEMPTS
                    {
                        next_time += time::Duration::days(1);
                        attempts += 1;
                    }

                    if attempts >= MAX_ATTEMPTS {
                        return None;
                    }
                }

                Some(next_time)
            }
            Task::Once(once_time, skip) => {
                if once_time <= now {
                    return None;
                }

                if let Some(skip_rules) = skip {
                    if skip_rules.iter().any(|s| s.is_skip(once_time)) {
                        return None;
                    }
                }

                Some(once_time)
            }
        }
    }
}

impl Task {
    /// Parse a task from a string with detailed error reporting.
    ///
    /// # Examples
    ///
    /// ```
    /// use easy_schedule::Task;
    ///
    /// let task = Task::parse("wait(10)").unwrap();
    ///
    /// match Task::parse("invalid") {
    ///     Ok(task) => println!("Success: {}", task),
    ///     Err(err) => println!("Error: {}", err),
    /// }
    /// ```
    pub fn parse(s: &str) -> Result<Self, String> {
        let s = s.trim();

        // Find the function name and arguments
        let open_paren = s.find('(').ok_or_else(|| {
            format!("Invalid task format: '{s}'. Expected format like 'wait(10)'")
        })?;

        let close_paren = s
            .rfind(')')
            .ok_or_else(|| format!("Missing closing parenthesis in: '{s}'"))?;

        if close_paren <= open_paren {
            return Err(format!("Invalid parentheses in: '{s}'"));
        }

        let function_name = s[..open_paren].trim();
        let args = s[open_paren + 1..close_paren].trim();

        // Parse arguments - check if there are skip conditions
        let (primary_arg, skip_conditions) = Self::parse_arguments(args)?;

        match function_name {
            "wait" => {
                let seconds = primary_arg.parse::<u64>().map_err(|_| {
                    format!("Invalid seconds value '{primary_arg}' in wait({primary_arg})")
                })?;
                Ok(Task::Wait(seconds, skip_conditions))
            }
            "interval" => {
                let seconds = primary_arg.parse::<u64>().map_err(|_| {
                    format!("Invalid seconds value '{primary_arg}' in interval({primary_arg})")
                })?;
                Ok(Task::Interval(seconds, skip_conditions))
            }
            "at" => {
                let format = format_description!("[hour]:[minute]");
                let time = Time::parse(&primary_arg, &format).map_err(|_| {
                    format!("Invalid time format '{primary_arg}' in at({primary_arg}). Expected format: HH:MM")
                })?;
                Ok(Task::At(time, skip_conditions))
            }
            "once" => {
                let format = format_description!(
                    "[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]"
                );
                let datetime = OffsetDateTime::parse(&primary_arg, &format)
                    .map_err(|_| format!("Invalid datetime format '{primary_arg}' in once({primary_arg}). Expected format: YYYY-MM-DD HH:MM:SS +HH"))?;
                Ok(Task::Once(datetime, skip_conditions))
            }
            _ => Err(format!(
                "Unknown task type '{function_name}'. Supported types: wait, interval, at, once"
            )),
        }
    }

    fn parse_arguments(args: &str) -> Result<(String, Option<Vec<Skip>>), String> {
        let args = args.trim();

        // Check if there's a comma, indicating skip conditions
        if let Some(comma_pos) = args.find(',') {
            let primary_arg = args[..comma_pos].trim().to_string();
            let skip_part = args[comma_pos + 1..].trim();

            let skip_conditions = Self::parse_skip_conditions(skip_part)?;
            Ok((primary_arg, Some(skip_conditions)))
        } else {
            Ok((args.to_string(), None))
        }
    }

    fn parse_skip_conditions(skip_str: &str) -> Result<Vec<Skip>, String> {
        let skip_str = skip_str.trim();

        // Check if it's a list format [...]
        if skip_str.starts_with('[') && skip_str.ends_with(']') {
            let list_content = &skip_str[1..skip_str.len() - 1];
            Self::parse_skip_list(list_content)
        } else {
            // Single skip condition
            let skip = Self::parse_single_skip(skip_str)?;
            Ok(vec![skip])
        }
    }

    fn parse_skip_list(list_str: &str) -> Result<Vec<Skip>, String> {
        let mut skips = Vec::new();
        let list_str = list_str.trim();

        if list_str.is_empty() {
            return Ok(skips);
        }

        // Split by comma and parse each skip condition
        for part in list_str.split(',') {
            let part = part.trim();
            if !part.is_empty() {
                let skip = Self::parse_single_skip(part)?;
                skips.push(skip);
            }
        }

        Ok(skips)
    }

    fn parse_single_skip(skip_str: &str) -> Result<Skip, String> {
        let skip_str = skip_str.trim();
        let parts: Vec<&str> = skip_str.split_whitespace().collect();

        if parts.is_empty() {
            return Err("Empty skip condition".to_string());
        }

        match parts[0] {
            "weekday" => {
                if parts.len() != 2 {
                    return Err(format!(
                        "Invalid weekday format: '{skip_str}'. Expected 'weekday N'"
                    ));
                }
                let day = parts[1]
                    .parse::<u8>()
                    .map_err(|_| format!("Invalid weekday number: '{}'", parts[1]))?;
                if !(1..=7).contains(&day) {
                    return Err(format!("Weekday must be between 1-7, got: {day}"));
                }
                Ok(Skip::Day(vec![day]))
            }
            "date" => {
                if parts.len() != 2 {
                    return Err(format!(
                        "Invalid date format: '{skip_str}'. Expected 'date YYYY-MM-DD'"
                    ));
                }
                let date_str = parts[1];
                let date_parts: Vec<&str> = date_str.split('-').collect();
                if date_parts.len() != 3 {
                    return Err(format!(
                        "Invalid date format: '{date_str}'. Expected 'YYYY-MM-DD'"
                    ));
                }

                let year = date_parts[0]
                    .parse::<i32>()
                    .map_err(|_| format!("Invalid year: '{}'", date_parts[0]))?;
                let month = date_parts[1]
                    .parse::<u8>()
                    .map_err(|_| format!("Invalid month: '{}'", date_parts[1]))?;
                let day = date_parts[2]
                    .parse::<u8>()
                    .map_err(|_| format!("Invalid day: '{}'", date_parts[2]))?;

                let month_enum =
                    time::Month::try_from(month).map_err(|_| format!("Invalid month: {month}"))?;
                let date = time::Date::from_calendar_date(year, month_enum, day)
                    .map_err(|_| format!("Invalid date: {year}-{month}-{day}"))?;

                Ok(Skip::Date(date))
            }
            "time" => {
                if parts.len() != 2 {
                    return Err(format!(
                        "Invalid time format: '{skip_str}'. Expected 'time HH:MM..HH:MM'"
                    ));
                }
                let time_range = parts[1];
                if let Some(range_pos) = time_range.find("..") {
                    let start_str = &time_range[..range_pos];
                    let end_str = &time_range[range_pos + 2..];

                    let format = format_description!("[hour]:[minute]");
                    let start_time = Time::parse(start_str, &format)
                        .map_err(|_| format!("Invalid start time: '{start_str}'"))?;
                    let end_time = Time::parse(end_str, &format)
                        .map_err(|_| format!("Invalid end time: '{end_str}'"))?;

                    Ok(Skip::TimeRange(start_time, end_time))
                } else {
                    // Single time
                    let format = format_description!("[hour]:[minute]");
                    let time = Time::parse(time_range, &format)
                        .map_err(|_| format!("Invalid time: '{time_range}'"))?;
                    Ok(Skip::Time(time))
                }
            }
            _ => Err(format!(
                "Unknown skip type: '{}'. Supported types: weekday, date, time",
                parts[0]
            )),
        }
    }
}

impl From<&str> for Task {
    /// Parse a task from a string, panicking on parse errors.
    ///
    /// For better error handling, consider using `Task::parse()` instead.
    ///
    /// # Panics
    ///
    /// Panics if the string cannot be parsed as a valid task.
    fn from(s: &str) -> Self {
        Task::parse(s).unwrap_or_else(|err| {
            panic!("Failed to parse task from string '{s}': {err}");
        })
    }
}

impl From<String> for Task {
    fn from(s: String) -> Self {
        Self::from(s.as_str())
    }
}

impl From<&String> for Task {
    fn from(s: &String) -> Self {
        Self::from(s.as_str())
    }
}

#[macro_export]
macro_rules! task {
    // 基础任务,无skip
    (wait $seconds:tt) => {
        $crate::Task::Wait($seconds, None)
    };
    (interval $seconds:tt) => {
        $crate::Task::Interval($seconds, None)
    };
    (at $hour:tt : $minute:tt) => {
        $crate::Task::At(
            time::Time::from_hms($hour, $minute, 0).unwrap(),
            None
        )
    };

    // 带单个skip条件
    (wait $seconds:tt, weekday $day:tt) => {
        $crate::Task::Wait($seconds, Some(vec![$crate::Skip::Day(vec![$day])]))
    };
    (wait $seconds:tt, date $year:tt - $month:tt - $day:tt) => {
        $crate::Task::Wait($seconds, Some(vec![$crate::Skip::Date(
            time::Date::from_calendar_date($year, time::Month::try_from($month).unwrap(), $day).unwrap()
        )]))
    };
    (wait $seconds:tt, time $start_h:tt : $start_m:tt .. $end_h:tt : $end_m:tt) => {
        $crate::Task::Wait($seconds, Some(vec![$crate::Skip::TimeRange(
            time::Time::from_hms($start_h, $start_m, 0).unwrap(),
            time::Time::from_hms($end_h, $end_m, 0).unwrap()
        )]))
    };

    (interval $seconds:tt, weekday $day:tt) => {
        $crate::Task::Interval($seconds, Some(vec![$crate::Skip::Day(vec![$day])]))
    };
    (interval $seconds:tt, date $year:tt - $month:tt - $day:tt) => {
        $crate::Task::Interval($seconds, Some(vec![$crate::Skip::Date(
            time::Date::from_calendar_date($year, time::Month::try_from($month).unwrap(), $day).unwrap()
        )]))
    };
    (interval $seconds:tt, time $start_h:tt : $start_m:tt .. $end_h:tt : $end_m:tt) => {
        $crate::Task::Interval($seconds, Some(vec![$crate::Skip::TimeRange(
            time::Time::from_hms($start_h, $start_m, 0).unwrap(),
            time::Time::from_hms($end_h, $end_m, 0).unwrap()
        )]))
    };

    (at $hour:tt : $minute:tt, weekday $day:tt) => {
        $crate::Task::At(
            time::Time::from_hms($hour, $minute, 0).unwrap(),
            Some(vec![$crate::Skip::Day(vec![$day])])
        )
    };
    (at $hour:tt : $minute:tt, date $year:tt - $month:tt - $day:tt) => {
        $crate::Task::At(
            time::Time::from_hms($hour, $minute, 0).unwrap(),
            Some(vec![$crate::Skip::Date(
                time::Date::from_calendar_date($year, time::Month::try_from($month).unwrap(), $day).unwrap()
            )])
        )
    };
    (at $hour:tt : $minute:tt, time $start_h:tt : $start_m:tt .. $end_h:tt : $end_m:tt) => {
        $crate::Task::At(
            time::Time::from_hms($hour, $minute, 0).unwrap(),
            Some(vec![$crate::Skip::TimeRange(
                time::Time::from_hms($start_h, $start_m, 0).unwrap(),
                time::Time::from_hms($end_h, $end_m, 0).unwrap()
            )])
        )
    };

    // 带多个skip条件列表
    (wait $seconds:tt, [$($skip:tt)*]) => {
        $crate::Task::Wait($seconds, Some($crate::task!(@build_skips $($skip)*)))
    };
    (interval $seconds:tt, [$($skip:tt)*]) => {
        $crate::Task::Interval($seconds, Some($crate::task!(@build_skips $($skip)*)))
    };
    (at $hour:tt : $minute:tt, [$($skip:tt)*]) => {
        $crate::Task::At(
            time::Time::from_hms($hour, $minute, 0).unwrap(),
            Some($crate::task!(@build_skips $($skip)*))
        )
    };

    // 辅助宏:构建skip列表
    (@build_skips) => { vec![] };
    (@build_skips weekday $day:tt $(, $($rest:tt)*)?) => {
        {
            let mut skips = vec![$crate::Skip::Day(vec![$day])];
            $(skips.extend($crate::task!(@build_skips $($rest)*));)?
            skips
        }
    };
    (@build_skips date $year:tt - $month:tt - $day:tt $(, $($rest:tt)*)?) => {
        {
            let mut skips = vec![$crate::Skip::Date(
                time::Date::from_calendar_date($year, time::Month::try_from($month).unwrap(), $day).unwrap()
            )];
            $(skips.extend($crate::task!(@build_skips $($rest)*));)?
            skips
        }
    };
    (@build_skips time $start_h:tt : $start_m:tt .. $end_h:tt : $end_m:tt $(, $($rest:tt)*)?) => {
        {
            let mut skips = vec![$crate::Skip::TimeRange(
                time::Time::from_hms($start_h, $start_m, 0).unwrap(),
                time::Time::from_hms($end_h, $end_m, 0).unwrap()
            )];
            $(skips.extend($crate::task!(@build_skips $($rest)*));)?
            skips
        }
    };
}

impl std::fmt::Display for Task {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Task::Wait(wait, skip) => {
                let skip = skip
                    .clone()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(", ");
                write!(f, "wait: {wait} {skip}")
            }
            Task::Interval(interval, skip) => {
                let skip = skip
                    .clone()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(", ");
                write!(f, "interval: {interval} {skip}")
            }
            Task::At(time, skip) => {
                let skip = skip
                    .clone()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(", ");
                write!(f, "at: {time} {skip}")
            }
            Task::Once(time, skip) => {
                let skip = skip
                    .clone()
                    .unwrap_or_default()
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(", ");
                write!(f, "once: {time} {skip}")
            }
        }
    }
}

pub fn get_next_time(now: OffsetDateTime, time: Time) -> OffsetDateTime {
    let mut next = now.replace_time(time);
    if next < now {
        next += time::Duration::days(1);
    }
    next
}

pub fn get_now(timezone_minutes: i16) -> Result<OffsetDateTime, time::error::ComponentRange> {
    let hours = timezone_minutes / 60;
    let minutes = timezone_minutes % 60;
    let offset = UtcOffset::from_hms(hours as i8, minutes as i8, 0)?;
    Ok(OffsetDateTime::now_utc().to_offset(offset))
}