title: Execute a code for 5 seconds and then stop it
body: <p>The goal of code is that, I want to make a random tcp traffic using iperf and capture it over 5, 10, 15, 20 seconds using tcpdump. In addition, capturing the throughput is also important for me. My problem is that, I would like to execute code1, code2, code3 and code4 for 5, 10, 15 and 20 seconds in bash. However I don't know how to put the mentioned condition for it. Here is my code:</p>
  
  <pre><code>  for Test_duration in 5 10 15 20
      do
      echo “Test performing with $Test_duration duration”
  
      sudo tcpdump -G 10 -W 2 -w /tmp/scripttest_$Test_duration -i h1-eth0 &amp;
  
      while true; do
  
      #code1
      time2=$(($RANDOM%20+1))&amp;
      pksize2=$(($RANDOM%1000+200))&amp;
      iperf -c 10.0.0.2 -t $time2 -r -l $pksize2  &gt;&gt; /media/sf_sharedsaeed/throughtput/iperthroughput_host2_$Test_duration.txt &amp;\
  
      #code2
      time3=$(($RANDOM%20+1))&amp;
      pksize3=$(($RANDOM%1000+200))&amp;
      iperf -c 10.0.0.3 -t $time3 -r -l $pksize3  &gt;&gt; /media/sf_sharedsaeed/throughtput/iperthroughput_host3_$Test_duration.txt &amp;\
  
      #code3
      time4=$(($RANDOM%20+1))&amp;
      pksize4=$(($RANDOM%1000+200))&amp;
      iperf -c 10.0.0.4 -t $time4 -r -l $pksize4  &gt;&gt; /media/sf_sharedsaeed/throughtput/iperthroughput_host4_$Test_duration.txt &amp;\
  
      #code4
      time5=$(($RANDOM%20+1))&amp;
      pksize5=$(($RANDOM%1000+200))&amp;
      iperf -c 10.0.0.5 -t $time5 -r -l $pksize5  &gt;&gt; /media/sf_sharedsaeed/throughtput/iperthroughput_host5_$Test_duration.txt &amp;\
  
      done
  
      done
  </code></pre>
  
  <p>Another constraint is that, code1, code2, code3 and code4 should be executed at the same time so, I used &amp;.
  Please help me what should I replace instead of <code>while true;</code> to have periodic execution of codes. Can any body help me? </p>