473,287 Members | 1,588 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,287 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 8962
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.