use postgres::{Client, NoTls};
use std::process::Command;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
fn is_program_running(program: &str) ->bool {
let cmdstr = format!("IMAGENAME eq {}", program);
let output = Command::new("cmd")
.arg("/S")
.arg("/c")
.arg("tasklist")
.arg("/FI")
.arg(cmdstr)
.output()
.expect("-1");
let output_str = String::from_utf8_lossy(&output.stdout);
let result = match output_str.find(program) {
Some(_) => true,
None => false
};
result
}
fn trigger_scheduled_task(taskname: &str) {
let cmdstr = format!("schtasks /RUN /TN {}", taskname);
Command::new("cmd")
.arg("/S")
.arg("/c")
.arg(cmdstr)
.output()
.expect("-1");
}
fn main() -> Result<(), postgres::Error> {
//数据库TODO
let mut client = Client::connect("host=localhost dbname=test user=postgres password=postgres", NoTls)?;
loop {
if is_program_running("notepad.exe") == false { //notepad TODO
for row in client.query(r"select cast(id as varchar) as id, tasktype
from saptask
where status='ongoing'", &[])? {
let id: &str = row.get(0);
let tasktype: &str = row.get(1);
let logpath = match tasktype { // address TODO
"MM" => r"D:\www\test\log.txt",
"BOM" => r"D:\www\test\log.txt",
_ => r"D:\www\test\log.txt",
};
let file = File::open(logpath).unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let linestr = line.unwrap_or_else(|_|{"".to_string()});
match &linestr.find("programfinished") {
Some(_) => {
let endtime = linestr.replace(" > programfinished ;", "");
let sqlid = str::parse::<i32>(&id).unwrap();
client.execute("update saptask
set endtime=$1,status='done'
where id=$2", &[&endtime, &sqlid])?;
},
_ => {}
}
}
}
}
for ongoingtask in client.query(r"select cast(count(id) as varchar) as q
from saptask
where status='ongoing'", &[])? {
let q :&str= ongoingtask.get(0);
if q.parse::<i32>().unwrap() == 0 {
for taskrow in client.query(r"select tasktype, taskfilepath
from saptask
where status='pending'
order by id asc
limit 1", &[])? {
let tasktype: &str = taskrow.get(0);
let taskfilepath: &str = taskrow.get(1);
match tasktype { // 1. 替换程序名称
"MM" => {
// 将newtaskaddr写入对应程序的txt文件里.然后去执行这个任务.
let newaddr= "D:/test/hello_rust.txt"; //TODO
let mut f = File::create(newaddr).unwrap();
f.write_all(taskfilepath.as_bytes()).unwrap();
println!("MM");},
"BOM" => {
// 将newtaskaddr写入对应程序的txt文件里.然后去执行这个任务.
let newaddr= "D:/test/hello_rust.txt"; //TODO
let mut f = File::create(newaddr).unwrap();
f.write_all(taskfilepath.as_bytes()).unwrap();
println!("BOM");
trigger_scheduled_task("do");
},
_ => {}
}
}
}
}
}
}