473,225 Members | 1,310 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,225 software developers and data experts.

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

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
Oct 25 '07 #1
5 8958
bartonc
6,596 Expert 4TB
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.
Oct 25 '07 #2
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.  
Oct 26 '07 #3
Smygis
126 100+
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.
Oct 26 '07 #4
Hi,
tks for your reply,

I did try your script but it
stop to :

# Enter Primary IP:
Oct 26 '07 #5
Smygis
126 100+
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!
Oct 26 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
54
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO...
31
by: Derek Fountain | last post by:
Does Python have a timer mechanism? i.e. an "after 500 milliseconds, run this bit of code" sort of thing?
8
by: Jonas Kölker | last post by:
Hello. I'm doing a Rubik's Cube timer, so I need a function to measure 100ths of a second. I've browsed through the library reference of python.org, but I didn't find anything that struck me as...
92
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption?...
4
by: Harro de Jong | last post by:
(absolute beginner here, sorry if this seems basic) Section 7.10 of 'How to Think Like a Computer Scientist' contains this discussion of string.find and other string functions: (quote) We can...
4
by: John Salerno | last post by:
My code is below. The main focus would be on the OnStart method. I want to make sure that a positive integer is entered in the input box. At first I tried an if/else clause, then switched to...
2
by: Thomas Ploch | last post by:
Hello folks, I am having troubles with implementing a timed queue. I am using the 'Queue' module to manage several queues. But I want a timed access, i.e. only 2 fetches per second max. I am...
10
by: DaTurk | last post by:
Hi, I'm creating an application that will need to use a timer to do a static method call every second. My question, is what would be the best timer to use? I know there are several, but I'd...
1
by: Robin Becker | last post by:
I've just been testing out Jakob Sievers' speedup of Python 2.5.2 by compiling on freebsd with gcc-4.3.3 (the standard freebsd 6.1 gcc is 3.4.4). I'm glad to say that his modification did improve...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.