Skip to main content

cron_task_scheduler/
http_tasks.rs

1use crate::models::{ReactiveTask, TaskContext, TaskType};
2use async_trait::async_trait;
3use reqwest::Client;
4use std::process::Command;
5use tracing::{info, error};
6
7#[derive(Debug)]
8pub struct HttpTask {
9    pub id: String,
10    pub url: String,
11    pub client: Client,
12}
13
14#[async_trait]
15impl ReactiveTask for HttpTask {
16
17    fn id(&self) -> &str {
18        &self.id
19    }
20
21    fn task_type(&self) -> TaskType {
22        TaskType::Async
23    }
24
25    async fn execute(
26        &self,
27        _context: TaskContext,
28    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
29        info!("Fetching URL: {}", self.url);
30        let res: reqwest::Response = self.client.get(&self.url).send().await?;
31        let status = res.status();
32        let body: String = res.text().await?;
33        info!(
34            "Response Status: {}, Body prefix: {}",
35            status,
36            &body[..std::cmp::min(body.len(), 50)]
37        );
38        Ok(())
39    }
40}
41
42#[derive(Debug)]
43pub struct SimpleLoggingTask {
44    pub id: String,
45}
46
47#[async_trait]
48impl ReactiveTask for SimpleLoggingTask {
49    fn id(&self) -> &str {
50        &self.id
51    }
52
53    fn task_type(&self) -> TaskType {
54        TaskType::Async
55    }
56
57    async fn execute(
58        &self,
59        context: TaskContext,
60    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
61        info!(
62            "Logging task {} executed. Scheduled: {:?}, Actual: {:?}",
63            self.id, context.scheduled_time, context.actual_time
64        );
65        Ok(())
66    }
67}
68
69#[derive(Debug)]
70pub struct CommandLineTask {
71    pub id: String,
72    pub command: String,
73    pub args: Vec<String>,
74}
75
76#[async_trait]
77impl ReactiveTask for CommandLineTask {
78    fn id(&self) -> &str {
79        &self.id
80    }
81
82    fn task_type(&self) -> TaskType {
83        TaskType::Blocking
84    }
85
86    async fn execute(
87        &self,
88        _context: TaskContext,
89    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
90        info!("Executing command: {} {:?}", self.command, self.args);
91
92        let output = Command::new(&self.command)
93            .args(&self.args)
94            .output()?;
95
96        if output.status.success() {
97            let stdout = String::from_utf8_lossy(&output.stdout);
98            info!("Command output: {}", stdout);
99        } else {
100            let stderr = String::from_utf8_lossy(&output.stderr);
101            error!("Command failed: {}", stderr);
102            return Err(format!("Command failed with status: {}", output.status).into());
103        }
104
105        Ok(())
106    }
107}