How many seconds left for a sleeping process to "wake up" - linux

I would like to know if there is a way to know how many seconds are left for a sleeping process (in 'S' status) to "wake up" in LINUX.
For example, a python process I put to sleep using the sleep method.
from time import sleep
sleep(60)
Thanks!

A process will sleep until an interrupt is sent. This may be from a software signal or some hardware via the o/s.

Depending on what you are trying to achieve, looking at this from the operating level might be an overkill. Instead consider solving it within your code, by splitting your sleep in multiple sleep statements and giving a update that way.
from time import sleep
for i in range(0,60):
sleep(1)
# Give an update status via i
print(f"I've slept {i} seconds")
Replace the print with something that gives an update to the OS, parses a value to a different programm etc, depending on your needs. This would be easier than trying to figure this out on an OS level.

Related

Sleep() Methods and OS - Scheduler (Camunda/Groovy)

I got a question for you guys and its not as specific as usual, which could make it a little annoying to answer.
The tool i'm working with is Camunda in combination with Groovy scripts and the goal is to reduce the maximum cpu load (or peak load). I'm doing this by "stretching" the work load over a certain time frame since the platform seems to be unhappy with huge work load inputs in a short amount of time. The resulting problem is that Camunda wont react smoothly when someone tries to operate it at the UI - Level.
So i wrote a small script which basically just lets each individual process determine his own "time to sleep" before running, if a certain threshold is exceeded. This is based on how many processes are trying to run at the same time as the individual process.
It looks like:
Process wants to start -> Process asks how many other processes are running ->
waitingTime = numberOfProcesses * timeToSleep * iterationOfMeasures
CPU-Usage Curve 1,3 without the Script. Curve 2,4 With the script
Testing it i saw that i could stretch the work load and smoothe out the UI - Levels. But now i need to describe why this is working exactly.
The Questions are:
What does a sleep method do exactly ?
What does the sleep method do on CPU - Level?
How does an OS-Scheduler react to a Sleep Method?
Namely: Does the scheduler reschedule or just simply "wait" for the time given?
How can i recreate and test the question given above?
The main goal is not for you to answer this, but could you give me a hint for finding the right Literature to answer these questions? Maybe you remember a book which helped you understand this kind of things or a Professor recommended something to you. (Mine wont answer, and i cant blame him)
I'm grateful for hints and or recommendations !
i'm sure you could use timer event
https://docs.camunda.org/manual/7.15/reference/bpmn20/events/timer-events/
it allows to postpone next task trigger for some time defined by expression.
about sleep in java/groovy: https://www.javamex.com/tutorials/threads/sleep.shtml
using sleep is blocking current thread in groovy/java/camunda.
so instead of doing something effective it's just blocked.

Squish Record and play in python

While recording activities in an application through squish in python, I want some wait time in between consecutive activities.
Which function should I use?
You can use the snooze function to suspend test execution for a certain time.
In general however, fixed-time delays are fragile and depend a lot on the system on which the test is executed (and the load of the system). A better approach might be to use the waitFor function to wait for some condition.
For instance, this code acquires a reference to a QPushButton object with the text OK and then suspends test execution until the buttom becomes disabled:
button = waitForObject("{type='QPushButton' text='OK'}")
waitFor(lambda: not button.enabled)
You can use sleep function. For example to put the script sleep for 2 seconds . (Eg:- sleep(2)). Dont forget to import datatime libraries . (Eg:- import time)
# going to sleep for 2 seconds
snooze(2)

Sleep loop in groovy for hour

hey getting used to groovy and i wanted to have a loop such as a do while loop in my groovy script which is ran every hour or 2 for until a certain condition inside the loop is met (variable = something). So I found the sleep step but was wondering if it would be ok to sleep for such a long time. The sleep function will not mess up right?
The sleep function will not mess up. But that isn't your biggest problem.
If all your script is doing is sleeping, it would be better to have a scheduler like Cron launch your script. This way is simpler and more resilient, it reduces the opportunities for the script to be accumulating garbage, leaking memory, having its JVM get killed by another process, or otherwise just falling into a bad state from programming errors. Cron is solid and there is less that can go wrong that way. Starting up a JVM is not speedy but if your timeframe is in hours it shouldn't be a problem.
Another possible issue is that the time your script wakes up may drift. The OS scheduler is not obliged to wake your thread up at exactly the elapsed time. Also the time on the server could be changed while the script is running. Using Cron would make the time your script acts more predictable.
On the other hand, with the scheduler, if a process takes longer than the time to the next run, there is the chance that multiple instances of the process can exist concurrently. You might want to have the script create a lock file and remove it once it's done, checking to see if the file exists already to let it know if another instance is still running.
First of all there's not do {} while() construct in groovy. Secondly it's a better idea to use a scheduler e.g. QuartzScheduler to run a cron task.

how to know if system is completely idle

I am trying to figure out, how can we know if the system is idle? I want to suspend the system if it is idle for some x minutes. I tried to find for this and tried the below script code as well
#!/bin/bash
idletime=$((1000*60)) # 1 minute in milliseconds
while true; do
idle=`xprintidle`
echo $idle
if (( $idle > $idletime )); then
echo -n "mem" >> /sys/power/state
fi
sleep 1
done
But xprintidle only monitors the mouse and keyboard activity to increment it's counter.
Now if I run a program in infinite loop then also it will suspend the system.
The other option was extracting the idle time from /proc/stat over an interval of time, but on different systems I see different range of values for cpu idle, if I leave the system without any activity.
Can some one help me how can I implement suspension of system.
Stuff can, and will, happen at any time. Something gets kicked off by cron. Someone's sleep() call finishes, and it wakes up for a few milliseconds.
I'd say, come up with some meaningful heuristic. For example, periodically sample /proc/loadavg, and if the load average stays below some threshold, for a given period of time, assume that the system is now idle.

Linux, timing out on subprocess

Ok, I need to write a code that calls a script, and if the operation in script hangs, terminates the process.
The preferred language is Python, but I'm also looking through C and bash script documentation too.
Seems like an easy problem, but I can't decide on the best solution.
From research so far:
Python: Has some weird threading model where the virtual machine uses
one thread at a time, won't work?
C: The preferred solution so far seems to use SIGALARM + fork +
execl. But SIGALARM is not heap safe, so it can trash everything?
Bash: timeout program? Not standard on all distros?
Since I'm a newbie to Linux, I'm probably unaware of 500 different gotchas with those functions, so can anyone tell me what's the safest and cleanest way?
Avoid SIGALRM because there is not much safe stuff to do inside the signal handler.
Considering the system calls that you should use, in C, after doing the fork-exec to start the subprocess, you can periodically call waitpid(2) with the WNOHANG option to inspect whether the subprocess is still running. If waitpid returns 0 (process is still running) and the desired timeout has passed, you can kill(2) the subprocess.
In bash you can do something similar to this:
start the script/program in background with &
get the process id of the background process
sleep for some time
and then kill the process (if it is finished you cannot kill it) or you can check if the process is still live and then to kill it.
Example:
sh long_time_script.sh &
pid=$!
sleep 30s
kill $pid
you can even try to use trap 'script_stopped $pid' SIGCHLD - see the bash man for more info.
UPDATE: I found other command timeout. It does exactly what you need - runs a command with a time limit. Example:
timeout 10s sleep 15s
will kill the sleep after 10 seconds.
There is a collection of Python code that has features to do exactly this, and without too much difficulty if you know the APIs.
The Pycopia collection has the scheduler module for timing out functions, and the proctools module for spawning subprocesses and sending signals to it. The kill method can be used in this case.

Resources