I have a bash script that runs indefinitely. I've searched high and low for a solution to add a timed event into the script that fires every 5 minutes, while the rest of the script keeps running. I can not have the script sleep, as it is constantly sending/receiving information to the server. Does anyone have any function or idea that will accomplish this. Basically I want it to send a specific command to the server every 300 seconds(5 minutes). I do not have access to make rewrite the server code to request the command every 5 minutes.
Basically the main script is similar to this:
#!/bin/bash
Var1="localhost"
Var2="2356"
Var3="DSDSASAQ"
Var4= "Admin"
#other variables as needed.
function fun1(){
#do some stuff
}
function fun2(){
#do some stuff
}
function fun3(){
#do some stuff
}
#Main code section.
exec 3<>/dev/tcp/${Var1}/${Var2}
echo "login Var4 Var3" >&3
While read LINE <&3;
do
#do some stuff
done
exit $?
Any help is appreciated. Also I have tried stuff like start=$SECONDS and duration=$SECONDS-$start and checked with if...then statements in the while loop, but it tends to fire the command off multiple times before it resets the start variable....the server likes to break link when it detects spam as well, so sending the same command that 10+ times in a short burst is not ideal.
Run a loop in a separate background process.
#!/bin/bash
...
#Main code section.
exec 3<>/dev/tcp/${Var1}/${Var2}
# watchdog
while sleep 300 & wait; do
echo "login Var4 Var3"
done >&3 &
trap "kill $!" EXIT
while read LINE <&3;
do
#do some stuff
done
exit $?
I think you tried out wrong if...then condition. Here is my shot at it ... and it should send the "special command" only once at the required time.
#!/bin/bash
# Set the "next time" when special command should be sent
((start=SECONDS+300))
while read LINE <&3; do
echo "do some stuff"
# Did we reach the "next time" ... if yes
if ((SECONDS>=start)); then
echo "special command"
# And now set the new "next time"
((start=SECONDS+300))
fi
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