I'm working on a program that updates the background of an x11 desktop at a specified interval. However, it eats large amounts of my CPU just sitting idle. I know this is due to the main loop running faster than I want it to. I've used a couple shameful hacks to quell usage down to about 15% but now I am searching for a long-term solution.
Here is the function that contains the main loop:
pub fn run_mapped(&mut self) {
info!(self.logger, "Running in mapped mode!");
let wait_d = Duration::new(0,500);
let long_wait_d = Duration::new(0,750);
loop {
if self.img_dir.1.elapsed() > self.reload_time {
self.img_dir.0.reload();
self.img_dir.1 = Instant::now();
}
let cd = self.x.get_current_desktop();
// change background if timeout is reached
if self.since_timeout.elapsed() > self.timeout {
self.change_backgrounds();
let ref mut current_bg = self.image_map[cd];
self.since_timeout = Instant::now();
self.x.change_background(current_bg);
}
match self.x.next_event() {
Some(_) => {
let ref mut current_bg = self.image_map[cd];
self.x.change_background(current_bg);
},
None => { sleep(wait_d); }
}
sleep(long_wait_d);
}
}
Not shown, but I have additionally set process priority lower to give more important process priority over this one.
I added the sleep calls to prevent >50% CPU usage but it still consumes ~20% which seems a little excessive for what I want this program to do. I'm looking at some of the CPU usage from other programs I'm running in my DE (candybar) and they're nowhere near as resource-hungry as my program.
All that being said, my two questions are:
Why is this? Meaning, why is my program using so much CPU since it is basically 'sleeping' most of the time (in its current state)?
How can I fix this? The only thing I can think of now is scrapping it and abusing cron jobs to the same effect.
The full code can be found on Github.