I have a few tasks that I run at irregular intervals on some of my servers.
Some of them actually eat up quite a bit of CPU – something that I don’t want on certain servers.
Running the task when the CPU is normally less used is nice, but I was looking for a way to start the task with a very low priority.
Basically, if anything else than that particular task wants the CPU, give it up. Otherwise, have a ball.
After a bit of search, what I found was the command called “nice“. “renice” is also nice. Uhm… well.. its not “nice“, but its nice.
Each task is given a “nice” level, which is the process’ stat about how nice it is with other processes when it comes to sharing the CPU. The “nice” level is used by the kernel to determine who gets the CPU’s attention.
Basically, the higher the level is, the more prone the task is to share CPU resources. The lower the level, the more selfish the process becomes.
The “nice” commands starts a process and assigns it a “nice” value, while “renice” allows you to change the “nice” value of an existing process.
For example, because I love examples, you could do the following weird backup command:
nice -n 20 zip -r /root/ugly_backup.zip /var/www/*
Which would start a low-priority (nice=20) task to recursively zip all of /var/www within the fule /root/ugly_backup.zip
(and people, please, don’t backup this way if you haven’t been forced to by someone with a gun or a big cheque)
NB: if you see your low-priority task run with a high CPU attribution, don’t panic – it just means that no other tasks is asking for CPU. And your web server’s CPU don’t have to sit on its tiny metaphorical sillicon hands while waiting for your visitors to take a peak at your awesome, (hopefully) relevant, web page.
While I’m in the process of writing this reminder note for myself, I feel that it is nice to add, for the benefit of my memory, that by ending a command line with an ampersand symbol &, the task will be started in the background.