0

I have a desktop computer with unix mint installed (mint is similar to ubuntu) and start some very CPU consuming jobs unattendedly before I go to sleep.

I would like to avoid that the computer runs for 2-3 hours and afterwards consumes energy just idling around the whole night long.

Therefore I would like to run a script every N minutes via crontab that checks whether my CPU's threads are idling for at least 5 minutes

(meaning: less then 10 percent CPU usage 5 minutes ago and less then 10 percent CPU usage right now).

If this is the case, the computer should be suspended with systemctl suspend.

I am quite familiar with Python and could implement this easily with it.

To run systemctl suspend would mean to execute the script as root.

Reading some other posts (like: https://stackoverflow.com/a/8314858), I got the impression that executing Python as root is not desirable because of security issues.

Is there perhaps a bash only implementation for my use case?

I have found e. g. https://unix.stackexchange.com/q/69167 but my bash skills are much less than my Python skills therefore I am looking for a way how to accomplish my task in bash only.

7824238
  • 388
  • 4
  • 14

1 Answers1

0

If you want to transfer data from one run of a cronjob to another, you should probably store data in a file. That would lead to something like:

prevrunfile=/tmp/something

prevcpu=$(cat $prevrunfile)
newcpu=$(top -b -n1 | grep "Cpu(s)" | awk '{print  $4}')

# do the logic with your CPU-stuff

echo $newcpu > $prevrunfile
Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31