8

I want to execute a task every 2 hours. Python has a Timer in Threading module, but does it meet my needs? How do I generate a proper Timer myself?

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
pat.inside
  • 1,724
  • 4
  • 17
  • 25

2 Answers2

18

If you want your code to be run every 2 hours the easiest way would be using cron or a similar scheduler depending on your operating system

if you want your programm to call a function every n seconds ( 7200 in your case ) you could use a thread and event.wait. The following example starts a timer that is triggered every second and prints a string to stdout

import threading
import time

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
            print "do something"
            self.event.wait( 1 )

    def stop(self):
        self.event.set()

tmr = TimerClass()
tmr.start()

time.sleep( 10 )

tmr.stop()
Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
  • @wok why? start is called once and used to do the setup, run is the method that does the work you want to do – Nikolaus Gradwohl Nov 11 '10 at 13:13
  • My mistake about the inheritance. – Wok Nov 11 '10 at 13:17
  • @NikolausGradwohl: expert solution! I was doing something similar but instead of using event, I passed a Queue object into that thread, and if timeout, I put something into that queue, and then the work thread can quit(work thread keeps checking the queue, if nothing, increment an integer by 1 for test purpose). However, after I run my program, the work thread will wait, but when it quits, I got no increment at all. Any idea what happened? Thanks. – Shang Wang May 04 '12 at 19:58
0

Can this be a solution.......

import time

    def fun1():
        print "Hi "

    while 1:

        fun1()
        time.sleep(5)

The function fun1 will be executed after every 5 sec. But i don't know if this is a good way to invoke a function after a specific time. Any drawbacks of this solution ?

Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63