473,406 Members | 2,217 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,406 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 8967
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.