Skip to content

Commit

Permalink
Added run_on_start feature to scheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
DenuxPlays committed Jan 15, 2025
1 parent 0d30d4b commit 3328f54
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/boot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ pub async fn run_scheduler<H: Hooks>(
println!("{scheduler}");
Ok(())
} else {
scheduler.run_on_start().await?;

Ok(scheduler.run().await?)
}
}
Expand Down
75 changes: 74 additions & 1 deletion src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub struct Config {
/// The default output setting for the jobs.
#[serde(default)]
pub output: Output,
#[serde(default)]
pub run_on_start: Vec<String>,
}

/// Representing a single job in the scheduler.
Expand Down Expand Up @@ -116,6 +118,7 @@ impl fmt::Display for Scheduler {
#[derive(Clone, Debug)]
pub struct Scheduler {
pub jobs: HashMap<String, Job>,
pub run_on_start: Vec<String>,
binary_path: PathBuf,
default_output: Output,
environment: Environment,
Expand Down Expand Up @@ -252,6 +255,7 @@ impl Scheduler {

Ok(Self {
jobs,
run_on_start: data.run_on_start.clone(),
binary_path: std::env::current_exe()?,
default_output: data.output.clone(),
environment: environment.clone(),
Expand Down Expand Up @@ -350,11 +354,35 @@ impl Scheduler {

Ok(())
}

pub async fn run_on_start(&self) -> Result<()> {
for job_name in &self.run_on_start {
if let Some(job) = self.jobs.get(job_name) {
let job_description =
job.prepare_command(&self.binary_path, &self.default_output, &self.environment);
match job_description.run() {
Ok(output) => {
tracing::info!(
status_code = output.status.code(),
"Executed job on start: {}",
job_name
);
}
Err(err) => {
tracing::error!(error = %err, "Failed to execute job on start: {}", job_name);
}
}
} else {
tracing::warn!("Job not found in run_on_start: {}", job_name);
}
}

Ok(())
}
}

#[cfg(test)]
mod tests {

use insta::assert_debug_snapshot;
use rstest::rstest;
use tests_cfg::db::AppHook;
Expand Down Expand Up @@ -526,4 +554,49 @@ mod tests {
>= 4
);
}

#[tokio::test]
async fn test_run_on_start() {
let tree_fs = tree_fs::TreeBuilder::default()
.drop(true)
.add("scheduler.txt", "")
.create()
.unwrap();

let environment = Environment::Development;

let job = Job {
run: format!(
"echo loco >> {}",
tree_fs.root.join("scheduler.txt").display()
),
shell: true,
cron: "0 0 * * *".to_string(),
tags: None,
output: None,
};

const JOB_NAME: &str = "test_job";
let mut jobs = HashMap::new();
jobs.insert(JOB_NAME.to_string(), job);

let scheduler = Scheduler {
jobs,
run_on_start: vec![JOB_NAME.to_string()],
binary_path: PathBuf::from("/usr/bin"),
default_output: Output::STDOUT,
environment,
};

let result = scheduler.run_on_start().await;

assert!(result.is_ok());
assert!(
std::fs::read_to_string(tree_fs.root.join("scheduler.txt"))
.unwrap()
.lines()
.count()
>= 1
);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
---
source: src/scheduler.rs
assertion_line: 405
expression: "format!(\"{scheduler}\")"
snapshot_kind: text
---
"# job_name schedule tags run\n1 print_task */5 * * * * * base, echo \"foo\"\n2 write_to_file */5 * * * * * base, write \"echo loco >> ./scheduler.txt\"\n"
"# job_name schedule tags run\n1 print_task */5 * * * * * base, echo \"foo\"\n2 run_on_start_task every 24 hours start \"echo \\\"Does this run on start?\\\" >> ./run_on_start.txt \"\n3 write_to_file */5 * * * * * base, write \"echo loco >> ./scheduler.txt\"\n"
1 change: 1 addition & 0 deletions src/tests_cfg/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub fn test_config() -> Config {
)]),

output: scheduler::Output::STDOUT,
run_on_start: vec![],
}),
}
}
11 changes: 10 additions & 1 deletion tests/fixtures/scheduler/scheduler.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,20 @@ jobs:
- base
- echo

write_to_file:
write_to_file:
run: "echo loco >> ./scheduler.txt"
shell: true
schedule: "*/5 * * * * *"
tags:
- base
- write

run_on_start_task:
run: "echo \"Does this run on start?\" >> ./run_on_start.txt "
shell: true
schedule: "every 24 hours"
tags:
- start

run_on_start:
- run_on_start_task

0 comments on commit 3328f54

Please sign in to comment.