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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charlie of Bolton
    New Member
    • Mar 2007
    • 32

    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
    Last edited by bartonc; Oct 25 '07, 10:58 PM.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    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.

    Comment

    • Charlie of Bolton
      New Member
      • Mar 2007
      • 32

      #3
      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 : ) !


      Code:
      insert time
      the_time = time.time()
      start_time = the_time
      end_time = the_time + (60*60*24)  # 24 hrs
      while the_time < end_time:
      # insert my code here ????????????????what I put here and How??
          time.sleep(60)    # wait 60 seconds
          the_time = time.time() # get the new time
      Code:
      def fil(data):
          patt = re.compile(r'\((\d+)% loss\)')
          patt1 = re.compile(r'(\d+.\d+.\d+.\d)')
       
          for line in data.split('\n'):
              
              if line.startswith("Ping statistics for"):
                  ip = patt1.search(line).group(1)
                  
              if patt.search(line):
                  loss_num = int(patt.search(line).group(1))
                  
                  if loss_num >= 2 :
                      s = open('c:/tmp/myprimarylogs.xls', 'a+')
                      s.write("%s '%s'\n" % (loss_num, ip))
                      s.close()
                      # if loss >= 2, return False - then secondary IPs are pinged
                      print 'loss_num is >= 2 ', loss_num
                      return False
                  else:
                      print 'loss_num is < 2,', loss_num
                      return True
       
      def ping(*fnames):
          g = open(fnames[0], 'w')
          for fn in fnames[1:]:
              f=open(fn, 'r')
              ipList = [line.strip() for line in f.readlines()]
              f.close()
              resList = []
              for ipAdd in ipList:
                  pingaling =os.popen("ping %s" %(ipAdd),"r")
                  data = pingaling.read()
                  resList.append(data)
                  # if loss > 2, ping secondary IPs
                  proceed = fil(data)
                  if proceed:
                      break       
              g.write('/n'.join(resList))
              if proceed:
                  break
          g.close()
       
      def get_IPs(fnP, fnS):
          while True:
              ipAddP = raw_input("# Enter Primary IP: ")
              if validIP(ipAddP):
                  f = open(fnP, 'w')
                  f.write(ipAddP.strip() + "\n")
                  f.close()
                  break
              else:
                  print "Invalid IP."
          ipList = []
          while True:
              while True:
                  ipAddS = raw_input("# Enter Secondary IP: ")
                  if validIP(ipAddS):
                      ipList.append(ipAddS.strip())
                      break
                  else:
                      print "Invalid IP"
              s = raw_input("# Enter another IP? Y/N: " )
              if s.upper() == "N":
                  f = open(fnS, 'w')
                  f.write('\n'.join(ipList))
                  f.close()
                  break
       
      fnP = 'c:/tmp/primaryip.xls'
      fnS = 'c:/tmp/secip.xls'
      fnW = 'c:/tmp/workfile.txt'
       
      get_IPs(fnP, fnS)
      ping(fnW, fnP, fnS)

      Comment

      • Smygis
        New Member
        • Jun 2007
        • 126

        #4
        Originally posted by Charlie of Bolton
        Loads of code
        something like:
        [code=python]
        #!/usr/bin/env python
        # coding: UTF-8

        import time
        import re
        import whateverelse

        fnP = 'c:/tmp/primaryip.xls'
        fnS = 'c:/tmp/secip.xls'
        fnW = 'c:/tmp/workfile.txt'

        def fil(data):
        ......

        def ping(*fnames):
        ......

        def get_IPs(fnP, fnS):
        ......

        def main():
        the_time = time.time()
        start_time = the_time # Youre not using start_time at all btw.
        end_time = the_time + (60*60*24) # 24 hrs
        while the_time < end_time:
        get_IPs(fnP, fnS)
        ping(fnW, fnP, fnS)
        time.sleep(60) # wait 60 seconds
        the_time = time.time() # get the new time


        if __name__ == "__main__":
        main()
        [/code]
        perhaps? Not many other ways of doing it.

        Comment

        • Charlie of Bolton
          New Member
          • Mar 2007
          • 32

          #5
          Hi,
          tks for your reply,

          I did try your script but it
          stop to :

          # Enter Primary IP:

          Comment

          • Smygis
            New Member
            • Jun 2007
            • 126

            #6
            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:
            [code=python]

            end_time = the_time + (60*60*24) # 24 hrs
            while the_time < end_time:
            get_IPs(fnP, fnS)
            ping(fnW, fnP, fnS)
            [/Code]
            is 'wrong' and shuld be this:
            [code=python]

            end_time = the_time + (60*60*24) # 24 hrs
            get_IPs(fnP, fnS)
            while the_time < end_time:
            ping(fnW, fnP, fnS)
            [/Code]

            <rant>
            WO! THERE IS A SLIMY LITTLE BUG IN THE CODE-TAGGS!

            Comment

            Working...