I have a script where i need to run a spicific function at certian intervals while the rest of the script executes normally.
For example... I want to get disk data every hour while the rest of the scripts gathers process data every second...
Here I have a basic script to test this but its not working as expected...
#!/bin/bash
function test () {
echo "This line should print all the time..."
}
function test2 () {
echo "This line should only print every 3 seconds..."
sleep 3
}
while :
do
test &
test2
done
Any help would be.... helpful :-D
Thanks!
Create a function with an infinite loop and a sleep, and start it in the background. It will periodically do stuff, while the rest of the script can continue.
periodic() {
while :; do
echo periodic
date
sleep 3
done
}
main() {
echo in the main...
sleep 5
echo still in the main...
sleep 1
echo in the main in the main in the main
}
periodic &
periodic_pid=$!
echo periodic_pid=$periodic_pid
main
echo time to stop
kill $periodic_pid
Run the periodic function in a background loop and use sleep to wait 3 seconds between iterations. If you need something done in the context of the main process, send it a signal from the background loop. Don't forget to kill your background processes at exit.
#!/bin/sh
terms=0
trap ' [ $terms = 1 ] || { terms=1; kill -TERM -$$; }; exit' EXIT INT HUP TERM QUIT
#In case the periodic stuff needs to run in the ctx of the main process
trap 'echo "In main ctx"' ALRM
test() {
echo "This line should print all the time..."
}
test2__loop()
{
while :; do
echo "This line should only print every 3 seconds..."
kill -ALRM $$
sleep 3
done
}
test2__loop &
while :
do
test
sleep 1
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With