Connecting Tech Pros Worldwide Forums | Help | Site Map

What's the best way to implement a timer in Python?

Member
 
Join Date: Mar 2007
Posts: 32
#1: Oct 25 '07
To complete my script, I would like to put a timer,
let say, I want the primary IP to be ping for 24 hrs, what
do you suggest me and than I stop anoying you : )

Brgds

bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,403
#2: Oct 26 '07

re: What's the best way to implement a timer in Python?


Quote:

Originally Posted by Charlie of Bolton

To complete my script, I would like to put a timer,
let say, I want the primary IP to be ping for 24 hrs, what
do you suggest me and than I stop annoying you : )

Brgds

I've also gotten pretty good at the whole 'site moderator' thing (ie: this new thread in your name).

It's really no annoyance. If we didn't enjoy this forum and the work entailed in keeping it alive and growing, we wouldn't be posting, etc. here.

Probably the best (safest) way to run a script periodically would be to schedule a task in the OS. Windows (in your case, I believe) uses the "Scheduled Tasks" applet in the Control Panel. On *nix, it's cron.

The reason for using the OS instead of a Python timer or scheduler is that the interface is guaranteed to be running even when your computer is first booted. If you would rather require that a Python script be running (it would be a great feature if you could shut down the task with out using the Task Manager (or ps)), then I could probably whip us some running examples which you could then fine tune. I strongly suggest the former solution, though.
Member
 
Join Date: Mar 2007
Posts: 32
#3: Oct 26 '07

re: What's the best way to implement a timer in Python?


Hi Bartonc,

I did the find the below script, to implement
a timer to ping each minute and stop in 24 hrs.
according to your script (below) where should I place
the following properly ? (did try several combinaisons but unsuc).
Or do you have a better idea ? (answer is probably yes : ) !


Expand|Select|Wrap|Line Numbers
  1.  
  2. insert time
  3. the_time = time.time()
  4. start_time = the_time
  5. end_time = the_time + (60*60*24)  # 24 hrs
  6. while the_time < end_time:
  7. # insert my code here ????????????????what I put here and How??
  8.     time.sleep(60)    # wait 60 seconds
  9.     the_time = time.time() # get the new time
  10.  
  11.  
Expand|Select|Wrap|Line Numbers
  1.  
  2. def fil(data):
  3.     patt = re.compile(r'\((\d+)% loss\)')
  4.     patt1 = re.compile(r'(\d+.\d+.\d+.\d)')
  5.  
  6.     for line in data.split('\n'):
  7.  
  8.         if line.startswith("Ping statistics for"):
  9.             ip = patt1.search(line).group(1)
  10.  
  11.         if patt.search(line):
  12.             loss_num = int(patt.search(line).group(1))
  13.  
  14.             if loss_num >= 2 :
  15.                 s = open('c:/tmp/myprimarylogs.xls', 'a+')
  16.                 s.write("%s '%s'\n" % (loss_num, ip))
  17.                 s.close()
  18.                 # if loss >= 2, return False - then secondary IPs are pinged
  19.                 print 'loss_num is >= 2 ', loss_num
  20.                 return False
  21.             else:
  22.                 print 'loss_num is < 2,', loss_num
  23.                 return True
  24.  
  25. def ping(*fnames):
  26.     g = open(fnames[0], 'w')
  27.     for fn in fnames[1:]:
  28.         f=open(fn, 'r')
  29.         ipList = [line.strip() for line in f.readlines()]
  30.         f.close()
  31.         resList = []
  32.         for ipAdd in ipList:
  33.             pingaling =os.popen("ping %s" %(ipAdd),"r")
  34.             data = pingaling.read()
  35.             resList.append(data)
  36.             # if loss > 2, ping secondary IPs
  37.             proceed = fil(data)
  38.             if proceed:
  39.                 break       
  40.         g.write('/n'.join(resList))
  41.         if proceed:
  42.             break
  43.     g.close()
  44.  
  45. def get_IPs(fnP, fnS):
  46.     while True:
  47.         ipAddP = raw_input("# Enter Primary IP: ")
  48.         if validIP(ipAddP):
  49.             f = open(fnP, 'w')
  50.             f.write(ipAddP.strip() + "\n")
  51.             f.close()
  52.             break
  53.         else:
  54.             print "Invalid IP."
  55.     ipList = []
  56.     while True:
  57.         while True:
  58.             ipAddS = raw_input("# Enter Secondary IP: ")
  59.             if validIP(ipAddS):
  60.                 ipList.append(ipAddS.strip())
  61.                 break
  62.             else:
  63.                 print "Invalid IP"
  64.         s = raw_input("# Enter another IP? Y/N: " )
  65.         if s.upper() == "N":
  66.             f = open(fnS, 'w')
  67.             f.write('\n'.join(ipList))
  68.             f.close()
  69.             break
  70.  
  71. fnP = 'c:/tmp/primaryip.xls'
  72. fnS = 'c:/tmp/secip.xls'
  73. fnW = 'c:/tmp/workfile.txt'
  74.  
  75. get_IPs(fnP, fnS)
  76. ping(fnW, fnP, fnS)
  77.  
  78.  
  79.  
Smygis's Avatar
Member
 
Join Date: Jun 2007
Posts: 100
#4: Oct 26 '07

re: What's the best way to implement a timer in Python?


Quote:

Originally Posted by Charlie of Bolton

Loads of code

something like:
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/env python
  2. # coding: UTF-8
  3.  
  4. import time
  5. import re
  6. import whateverelse
  7.  
  8. fnP = 'c:/tmp/primaryip.xls'
  9. fnS = 'c:/tmp/secip.xls'
  10. fnW = 'c:/tmp/workfile.txt'
  11.  
  12. def fil(data):
  13.     ......
  14.  
  15. def ping(*fnames):
  16.     ......
  17.  
  18. def get_IPs(fnP, fnS):
  19.     ......
  20.  
  21. def main():
  22.     the_time = time.time()
  23.     start_time = the_time # Youre not using start_time at all btw.
  24.     end_time = the_time + (60*60*24)  # 24 hrs
  25.     while the_time < end_time:
  26.         get_IPs(fnP, fnS)
  27.         ping(fnW, fnP, fnS)
  28.         time.sleep(60)    # wait 60 seconds
  29.         the_time = time.time() # get the new time
  30.  
  31.  
  32. if __name__ == "__main__":
  33.     main()
  34.  
perhaps? Not many other ways of doing it.
Member
 
Join Date: Mar 2007
Posts: 32
#5: Oct 26 '07

re: What's the best way to implement a timer in Python?


Hi,
tks for your reply,

I did try your script but it
stop to :

# Enter Primary IP:
Smygis's Avatar
Member
 
Join Date: Jun 2007
Posts: 100
#6: Oct 27 '07

re: What's the best way to implement a timer in Python?


Quote:

Originally Posted by Charlie of Bolton

Hi,
tks for your reply,

I did try your script but it
stop to :

# Enter Primary IP:

Sorry to say it but your code makes no sense at all.
You use several functions that are never defined somwhere.

But i do know that this part:
Expand|Select|Wrap|Line Numbers
  1.  
  2.     end_time = the_time + (60*60*24)  # 24 hrs
  3.     while the_time < end_time:
  4.         get_IPs(fnP, fnS)
  5.         ping(fnW, fnP, fnS)
  6.  
is 'wrong' and shuld be this:
Expand|Select|Wrap|Line Numbers
  1.  
  2.     end_time = the_time + (60*60*24)  # 24 hrs
  3.     get_IPs(fnP, fnS)
  4.     while the_time < end_time:
  5.         ping(fnW, fnP, fnS)
  6.  
<rant>
WO! THERE IS A SLIMY LITTLE BUG IN THE CODE-TAGGS!
Reply