armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
# Cron Job Scheduling Guide

Armature provides a robust cron job scheduler for running periodic tasks in your application.

## Features

- ✅ Standard cron expression syntax
- ✅ Named jobs with metadata
- ✅ Async job execution
- ✅ Job lifecycle management
- ✅ Error handling and retry logic
- ✅ Job overlap prevention
- ✅ Job enable/disable at runtime
- ✅ Job statistics and monitoring

## Table of Contents

- [Basic Usage]#basic-usage
- [Cron Expressions]#cron-expressions
- [Job Context]#job-context
- [Scheduler Configuration]#scheduler-configuration
- [Job Management]#job-management
- [Error Handling]#error-handling
- [Job Statistics]#job-statistics
- [Common Patterns]#common-patterns
- [Best Practices]#best-practices

## Basic Usage

### Creating a Scheduler

```rust
use armature_cron::*;

#[tokio::main]
async fn main() -> Result<(), CronError> {
    let mut scheduler = CronScheduler::new();

    // Add jobs
    scheduler.add_job(
        "my_job",
        "0 * * * * *", // Every minute
        |ctx| Box::pin(async move {
            println!("Job executed!");
            Ok(())
        })
    )?;

    // Start the scheduler
    scheduler.start().await?;

    // Keep running
    tokio::signal::ctrl_c().await?;

    // Stop the scheduler
    scheduler.stop().await?;

    Ok(())
}
```

### Adding Jobs

```rust
// Simple job
scheduler.add_job(
    "heartbeat",
    "*/5 * * * * *", // Every 5 seconds
    |ctx| Box::pin(async move {
        println!("Heartbeat");
        Ok(())
    })
)?;

// Job with shared state
let counter = Arc::new(AtomicU32::new(0));
let counter_clone = counter.clone();

scheduler.add_job(
    "counter",
    "0 * * * * *", // Every minute
    move |ctx| {
        let counter = counter_clone.clone();
        Box::pin(async move {
            let count = counter.fetch_add(1, Ordering::SeqCst);
            println!("Count: {}", count + 1);
            Ok(())
        })
    }
)?;
```

## Cron Expressions

### Format

Cron expressions consist of 6 fields:

```
┌───────────── second (0-59)
│ ┌───────────── minute (0-59)
│ │ ┌───────────── hour (0-23)
│ │ │ ┌───────────── day of month (1-31)
│ │ │ │ ┌───────────── month (1-12 or JAN-DEC)
│ │ │ │ │ ┌───────────── day of week (0-6 or SUN-SAT, 0=Sunday)
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *
```

### Special Characters

- `*` - Any value
- `,` - Value list separator (e.g., `1,3,5`)
- `-` - Range (e.g., `1-5`)
- `/` - Step values (e.g., `*/5` = every 5)

### Common Expressions

```rust
use armature_cron::CronPresets;

// Every second
"* * * * * *"

// Every minute
"0 * * * * *"
// or
CronPresets::EVERY_MINUTE

// Every 5 minutes
"0 */5 * * * *"
CronPresets::EVERY_5_MINUTES

// Every hour
"0 0 * * * *"
CronPresets::EVERY_HOUR

// Every day at midnight
"0 0 0 * * *"
CronPresets::DAILY

// Every Monday at 9 AM
"0 0 9 * * MON"

// Weekdays at 9 AM
"0 0 9 * * MON-FRI"
CronPresets::WEEKDAYS_9AM

// First day of every month
"0 0 0 1 * *"
CronPresets::MONTHLY

// Every 15 minutes during business hours (9 AM - 5 PM)
"0 */15 9-17 * * *"

// Every weekend at 10 AM
"0 0 10 * * SAT,SUN"
CronPresets::WEEKENDS_10AM
```

## Job Context

Every job receives a `JobContext` with information about the execution:

```rust
scheduler.add_job(
    "report",
    "0 * * * * *",
    |ctx| Box::pin(async move {
        println!("Job name: {}", ctx.name);
        println!("Scheduled time: {}", ctx.scheduled_time);
        println!("Actual time: {}", ctx.execution_time);
        println!("Execution count: {}", ctx.execution_count);
        println!("Delay: {:?}", ctx.delay());
        Ok(())
    })
)?;
```

### JobContext Fields

```rust
pub struct JobContext {
    /// Job name
    pub name: String,

    /// When the job was scheduled to run
    pub scheduled_time: DateTime<Utc>,

    /// When the job actually started running
    pub execution_time: DateTime<Utc>,

    /// Number of times this job has executed (0-based)
    pub execution_count: u64,
}
```

## Scheduler Configuration

### Custom Configuration

```rust
use std::time::Duration;

let config = SchedulerConfig {
    // How often to check for jobs to run
    tick_interval: Duration::from_secs(1),

    // Whether to run jobs that were missed during downtime
    run_missed_jobs: false,

    // Maximum number of jobs to run concurrently
    max_concurrent_jobs: 10,

    // Whether to log job execution
    log_execution: true,
};

let mut scheduler = CronScheduler::with_config(config);
```

### Default Configuration

```rust
SchedulerConfig {
    tick_interval: Duration::from_secs(1),
    run_missed_jobs: false,
    max_concurrent_jobs: 10,
    log_execution: true,
}
```

## Job Management

### Listing Jobs

```rust
let jobs = scheduler.list_jobs().await;
for job_name in jobs {
    println!("Job: {}", job_name);
}
```

### Enabling/Disabling Jobs

```rust
// Disable a job (it won't run but stays in the scheduler)
scheduler.disable_job("my_job").await?;

// Re-enable a job
scheduler.enable_job("my_job").await?;
```

### Removing Jobs

```rust
// Completely remove a job from the scheduler
scheduler.remove_job("my_job").await?;
```

### Checking Status

```rust
// Check if scheduler is running
if scheduler.is_running().await {
    println!("Scheduler is active");
}
```

## Error Handling

### Handling Job Errors

```rust
scheduler.add_job(
    "api_sync",
    "0 */5 * * * *",
    |ctx| Box::pin(async move {
        match fetch_api_data().await {
            Ok(data) => {
                process_data(data).await?;
                Ok(())
            }
            Err(e) => {
                eprintln!("Failed to fetch API data: {}", e);
                Err(CronError::ExecutionFailed(e.to_string()))
            }
        }
    })
)?;
```

### Error Types

```rust
pub enum CronError {
    /// Invalid cron expression
    InvalidExpression(String),

    /// Job not found
    JobNotFound(String),

    /// Job already exists
    JobAlreadyExists(String),

    /// Job execution failed
    ExecutionFailed(String),

    /// Scheduler not running
    SchedulerNotRunning,

    /// Scheduler already running
    SchedulerAlreadyRunning,

    /// Configuration error
    Config(String),

    /// Generic error
    Other(String),
}
```

## Job Statistics

### Getting Job Stats

```rust
let stats = scheduler.get_stats("my_job").await?;

println!("Job: {}", stats.name);
println!("Enabled: {}", stats.enabled);
println!("Executions: {}", stats.execution_count);

if let Some(last_run) = stats.last_run {
    println!("Last run: {}", last_run);
}

if let Some(next_run) = stats.next_run {
    println!("Next run: {}", next_run);
}

match stats.status {
    JobStatus::Scheduled => println!("Status: Waiting"),
    JobStatus::Running => println!("Status: Running"),
    JobStatus::Completed => println!("Status: Completed"),
    JobStatus::Failed(err) => println!("Status: Failed - {}", err),
}
```

## Common Patterns

### Database Cleanup Job

```rust
scheduler.add_job(
    "cleanup_old_records",
    "0 0 2 * * *", // 2 AM daily
    |ctx| Box::pin(async move {
        let db = get_database_connection().await?;

        let deleted = db.execute(
            "DELETE FROM sessions WHERE expires_at < NOW()"
        ).await?;

        println!("Deleted {} expired sessions", deleted);
        Ok(())
    })
)?;
```

### Report Generation

```rust
scheduler.add_job(
    "daily_report",
    "0 0 8 * * MON-FRI", // 8 AM on weekdays
    |ctx| Box::pin(async move {
        let report = generate_daily_report().await?;
        send_email_report(report).await?;
        println!("Daily report sent");
        Ok(())
    })
)?;
```

### Cache Warming

```rust
scheduler.add_job(
    "warm_cache",
    "0 */15 * * * *", // Every 15 minutes
    |ctx| Box::pin(async move {
        let cache = get_cache().await?;
        let data = fetch_frequently_accessed_data().await?;
        cache.set("popular_items", data, Some(Duration::from_secs(900))).await?;
        Ok(())
    })
)?;
```

### API Rate Limit Reset

```rust
scheduler.add_job(
    "reset_rate_limits",
    "0 0 * * * *", // Every hour
    |ctx| Box::pin(async move {
        let limiter = get_rate_limiter().await?;
        limiter.reset_hourly_limits().await?;
        println!("Rate limits reset");
        Ok(())
    })
)?;
```

### Health Check

```rust
scheduler.add_job(
    "health_check",
    "*/30 * * * * *", // Every 30 seconds
    |ctx| Box::pin(async move {
        let status = check_service_health().await?;

        if !status.is_healthy {
            send_alert("Service unhealthy").await?;
        }

        Ok(())
    })
)?;
```

## Best Practices

### 1. Prevent Job Overlap

Jobs automatically prevent overlapping executions by default:

```rust
// This is enabled by default
job.prevent_overlap = true;
```

If a job is still running when its next scheduled time arrives, it will be skipped.

### 2. Use Appropriate Intervals

Don't schedule jobs too frequently:

```rust
// ❌ Bad: Too frequent, might cause performance issues
"* * * * * *" // Every second

// ✅ Good: Reasonable interval
"0 */5 * * * *" // Every 5 minutes
```

### 3. Handle Errors Gracefully

```rust
scheduler.add_job(
    "resilient_job",
    "0 * * * * *",
    |ctx| Box::pin(async move {
        let result = risky_operation().await;

        match result {
            Ok(data) => {
                process(data).await?;
                Ok(())
            }
            Err(e) => {
                // Log error but don't crash
                eprintln!("Job failed: {}", e);
                // Optionally return error to mark job as failed
                Err(CronError::ExecutionFailed(e.to_string()))
            }
        }
    })
)?;
```

### 4. Use Shared State Carefully

```rust
use std::sync::Arc;
use tokio::sync::RwLock;

let shared_state = Arc::new(RwLock::new(AppState::new()));
let state_clone = shared_state.clone();

scheduler.add_job(
    "state_job",
    "0 * * * * *",
    move |ctx| {
        let state = state_clone.clone();
        Box::pin(async move {
            let mut state = state.write().await;
            state.update().await?;
            Ok(())
        })
    }
)?;
```

### 5. Monitor Job Execution

```rust
// Periodically check job statistics
scheduler.add_job(
    "monitor",
    "0 */10 * * * *", // Every 10 minutes
    |ctx| Box::pin(async move {
        let stats = get_all_job_stats().await?;

        for stat in stats {
            if let JobStatus::Failed(err) = stat.status {
                send_alert(&format!("Job {} failed: {}", stat.name, err)).await?;
            }
        }

        Ok(())
    })
)?;
```

### 6. Graceful Shutdown

```rust
#[tokio::main]
async fn main() -> Result<(), CronError> {
    let mut scheduler = CronScheduler::new();

    // Add jobs...

    scheduler.start().await?;

    // Wait for shutdown signal
    tokio::signal::ctrl_c().await?;

    println!("Shutting down scheduler...");
    scheduler.stop().await?;

    // Wait for running jobs to complete
    tokio::time::sleep(Duration::from_secs(5)).await;

    println!("Shutdown complete");
    Ok(())
}
```

### 7. Use Job Metadata

```rust
// Jobs support metadata for additional information
let mut job = Job::new("backup", expression, handler);
job.set_metadata("environment", "production");
job.set_metadata("priority", "high");
job.set_metadata("owner", "ops-team");
```

## Integration with Armature

### Using with Dependency Injection

```rust
use armature_framework::prelude::*;
use armature_cron::*;

#[injectable]
struct CronService {
    scheduler: Arc<RwLock<CronScheduler>>,
}

impl CronService {
    pub fn new() -> Self {
        Self {
            scheduler: Arc::new(RwLock::new(CronScheduler::new())),
        }
    }

    pub async fn setup_jobs(&self) -> CronResult<()> {
        let mut scheduler = self.scheduler.write().await;

        scheduler.add_job(
            "cleanup",
            "0 0 * * * *",
            |ctx| Box::pin(async move {
                // Job logic
                Ok(())
            })
        )?;

        scheduler.start().await?;
        Ok(())
    }
}

#[module]
struct AppModule {
    providers: vec![CronService::provider()],
}
```

### HTTP Endpoints for Job Management

```rust
#[controller("/api/cron")]
struct CronController {
    cron_service: CronService,
}

#[routes]
impl CronController {
    #[get("/jobs")]
    async fn list_jobs(&self) -> Json<Vec<String>> {
        let scheduler = self.cron_service.scheduler.read().await;
        Json(scheduler.list_jobs().await)
    }

    #[post("/jobs/:name/enable")]
    async fn enable_job(&self, #[param] name: String) -> Result<HttpResponse, Error> {
        let scheduler = self.cron_service.scheduler.read().await;
        scheduler.enable_job(&name).await
            .map_err(|e| Error::BadRequest(e.to_string()))?;
        Ok(HttpResponse::ok("Job enabled"))
    }

    #[post("/jobs/:name/disable")]
    async fn disable_job(&self, #[param] name: String) -> Result<HttpResponse, Error> {
        let scheduler = self.cron_service.scheduler.read().await;
        scheduler.disable_job(&name).await
            .map_err(|e| Error::BadRequest(e.to_string()))?;
        Ok(HttpResponse::ok("Job disabled"))
    }

    #[get("/jobs/:name/stats")]
    async fn get_stats(&self, #[param] name: String) -> Result<Json<JobStats>, Error> {
        let scheduler = self.cron_service.scheduler.read().await;
        let stats = scheduler.get_stats(&name).await
            .map_err(|e| Error::NotFound(e.to_string()))?;
        Ok(Json(stats))
    }
}
```

## Summary

The Armature cron system provides:

- **Standard cron syntax** for familiar scheduling
-**Async execution** for non-blocking jobs
-**Job management** with enable/disable/remove operations
-**Statistics** for monitoring and debugging
-**Error handling** with detailed error types
-**Overlap prevention** to avoid concurrent executions
-**Integration** with Armature's DI system

Perfect for:
- Database maintenance
- Report generation
- Cache warming
- Data synchronization
- Health checks
- Rate limit resets
- Cleanup tasks
- Scheduled notifications

For more examples, see `examples/cron_jobs.rs`.