Timer event in Bash

I have a bash script that runs indefinitely. I searched high and low for a solution to add a timing event to the script that fires every 5 minutes and the rest of the script keeps running. I cannot sleep the script as it is constantly sending / receiving information to the server. Does anyone have any features or ideas that will achieve this. Basically I want it to send a specific command to the server every 300 seconds (5 minutes). I don't have access to rewrite the server code to request a command every 5 minutes.

Basically the main script is like this one:

#!/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 tried things like start = $ SECONDS and duration = $ SECONDS- $ start and checked with if ... then statements in a while loop, but it runs the command multiple times before it resets the start variable ... the server likes to break communication when detects spam, so sending the same command 10+ times in a short burst is not ideal.

+3


source to share


3 answers


I think you are wrong if ... then the condition. Here's my snapshot ... and it only has to send a "special command" once at the right 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

      

+1


source


Start the 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 $?

      

+3


source


There are many ways to do it cron

, watch

or even while sleep

, all come to mind.

look

watch -n300 command

      

during sleep

while sleep 300; do command; done

      

hron

* * * * * sleep 300; command

      

There are other ways as well, but one of these methods will probably work for your question.

0


source







All Articles