How to run a process when the computer is idle?

Hi there,

I wrote a script that scans a folder for new files.
I don't want to run it at specific times but only when the computer is NOT busy.

I tried to use nice but it doesn't really work. I mean, even if my process has less priority, it still slows down the other processes. I did a test to check that. The following command creates a dummy file of 256 MB:

dd if=/dev/zero of=dummy bs=1048576 count=256 2> /dev/null

It lasts 20 seconds

If I run this command two times at the same time, one in normal mode, the other one with nice, I get the following times:
normal=35 seconds
niced=45 seconds

What I'm trying to do is that one command runs without being slowed down and the other command simply waits untill it can run without slowing down other processes.

Am I clear enough? Don't hesitate to ask for more information if you can help me.

Thanks in advance
Santiago

There's a small logical error in your example: nice only advises the process scheduler, and a high niceness doesn't mean that the process will wait 'till nothing else is running. It just means that those processes with a lower niceness will run first, and after they're done or waiting it'll get CPU time just like the others.
Besides, the example you've given is probably more influenced by I/O waits of 2 (or more) processes accessing the HDD than the scheduler.

As for your problem, you could check the first or second field of /proc/loadavg (1 / 5 minute load average), and depending on that start your process. It can't, however, predict whether or not another, CPU intensive, process will start just 5 seconds after.

Thanks Pludi for your answer,

That's exactly what I'm afraid of.

So you mean there's no way to run a process that would always let the others go before it? Is this correct?

What I'm gonna do is check for /proc/loadavg and run the process with low priority (high niceness). Do you consider a better solution?

Santiago

There are 2 immediate things that I can think of:

  • Advising the process scheduler via nice
  • Advising the I/O scheduler via ionice

Other than that you could look for periods of time where the system is almost idle, and only allow your program to run during those periods. But that would have to be done manually, as it's non-trivial to code (IMO). Software like BOINC just wait for a certain time of no user input to determine "idle".

Or, if you know that the process will be very CPU intensive for a short period of time, start it with a very low niceness, so that impact on the system will be as short as possible.