224

Is there a way to, for example, print Hello World! every n seconds? For example, the program would go through whatever code I had, then once it had been 5 seconds (with time.sleep()) it would execute that code. I would be using this to update a file though, not print Hello World.

For example:

startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds

for i in range(5):
    print(i)

>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4
3

7 Answers 7

442
import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

22
  • 47
    OK, fixed, note that you may also want to set the thread made by Timer as a daemon in case you want to interrupt the program cleanly by just finishing the main thread -- in that case you'd better set t = threading.Timer &c, then t.daemon = True, and only then t.start() right before the print "Hello, World!". Commented Aug 3, 2010 at 5:46
  • 9
    @YanKingYin: try to run it. It does repeat. printit schedules itself.
    – jfs
    Commented Sep 18, 2014 at 7:33
  • 28
    wouldn't this eventually hit the recursive function limit?
    – Dani
    Commented Mar 14, 2018 at 13:12
  • 18
    How do I stop it?
    – Daksh Shah
    Commented Apr 12, 2018 at 13:21
  • 9
    @AbelSurace Calling the function recursively is not the same as launching a new thread to run the function. The first adds to the recursion depth of the current thread and the other doesn't.
    – moooeeeep
    Commented Oct 31, 2018 at 11:41
158

My humble take on the subject, a generalization of Alex Martelli's answer, with start() and stop() control:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()
    
    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)
    
    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True
    
    def stop(self):
        self._timer.cancel()
        self.is_running = False

Usage:

from time import sleep

def hello(name):
    print "Hello %s!" % name

print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
    sleep(5) # your long-running job goes here...
finally:
    rt.stop() # better in a try/finally block to make sure the program ends!

Features:

  • Standard library only, no external dependencies
  • start() and stop() are safe to call multiple times even if the timer has already started/stopped
  • function to be called can have positional and named arguments
  • You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!
10
  • 2
    @JossieCalderon: The sleep() function is in the time module from Python's Standard Library, no need of any additional code to use it besides the import. But please note this is a one-time blocking call, not a repeated multi-threaded timer as the OP requested. Basically, sleep() is just a pause, not a timer.
    – MestreLion
    Commented Jul 11, 2016 at 22:08
  • 9
    This is nice, but note that it doesn't run the job every n seconds. Instead, it runs a n-second timer, then quickly starts another n-second timer... but there is a delay before the next timer starts. So this doesn't fire precisely every n seconds; rather, it drifts, with a bit more than n seconds between jobs. A 1 second timer running a job to print the current time yields: starting... 16:07:42.017682 16:07:43.023215 16:07:44.023626 etc.
    – eraoul
    Commented Dec 5, 2016 at 0:10
  • 3
    Yes, @eraoul , it does drift as there is no straightforward way to set a truly recurring timer using Python's Standard Library, so I "chained" several one-time timers to simulate it. The drift, however, was 5ms on first run and 0.4ms on the following, so it would take approximately somewhere from 200 to 2500 runs to drift a whole second, which might or might not be significant for you. For more accuracy over thousands of runs one could either calculate the next run based on the RTC or use an external tool such as cron
    – MestreLion
    Commented Feb 6, 2017 at 16:08
  • 1
    Thank you for this. I added self._timer.daemon = True to handle shutdowns better and moved the function call right after self._timer.start() to have it run immediately.
    – fafl
    Commented Aug 1, 2017 at 9:51
  • 1
    @Sarthak: stop the timer you say? You could either add some logic to the called function to check elapsed time (comparing current time with a global, previously saved start time) or create another 30-minute timer, both approaches would disable the repeated timer (and also itself in case of the second timer)
    – MestreLion
    Commented Apr 1, 2020 at 7:40
34

Save yourself a schizophrenic episode and use the Advanced Python scheduler:

The code is so simple:

from apscheduler.scheduler import Scheduler

sched = Scheduler()
sched.start()

def some_job():
    print "Every 10 seconds"

sched.add_interval_job(some_job, seconds = 10)

....
sched.shutdown()
4
  • 11
    First of all, the submodule is called 'schedulers', with an 's'. And there is no class Scheduler in there. Maybe BackgroundScheduler? Anyway, this answer is incomplete and does not work. Commented Aug 26, 2014 at 9:04
  • 4
    It's been a while, I guess I pasted the code from the web user manual. The above code is now corrected (still not tested, but it comes from my own working code and I am using it constantly). PS: maybe we are looking at different versions / modules? I'm sure my line is "from apscheduler.scheduler import Scheduler" with capital S and not plural. Commented Aug 30, 2014 at 8:03
  • 3
    @MadsSkjern: I see that 2.1 branch has apscheduler.scheduler (no s) module. The current branch 3 does not.
    – jfs
    Commented Sep 18, 2014 at 7:43
  • 17
    Anyone looking at this answer now (Nov 2014) should be aware that this, while a good answer, is all wrong. The above comments discuss this. To add a job in the current version the code would read sched.add_job(some_job, 'interval', seconds = 10). Look at the documentation
    – Wapiti
    Commented Nov 22, 2014 at 6:12
30
def update():
    import time
    while True:
        print 'Hello World!'
        time.sleep(5)

That'll run as a function. The while True: makes it run forever. You can always take it out of the function if you need.

8
  • 6
    Doesn't work; it just runs forever and I cant do anything else while it is. Commented Aug 3, 2010 at 5:16
  • What other things do you want to be doing at the same time? Commented Aug 3, 2010 at 5:19
  • 20
    Well this just runs in a loop. You didn't specify in the question that you'd be doing something else in the meantime so I assumed that's what you need.
    – avacariu
    Commented Aug 3, 2010 at 5:54
  • 11
    Note: This will not quite run every 5 seconds. It will run every 5 + N seconds, where N is the time it takes to execute the time between while True: and time.sleep(5). While this is negligible for print 'Hellow World!' in comparison to 5 whole seconds, it may be nontrivial for other scenarios. I should note that using threads won't quite get it to 5 seconds exactly either, but it will be closer.
    – Quelklef
    Commented Oct 7, 2017 at 1:02
  • 3
    I know I'm like 9 years too late, but this isn't a valid solution, he specifically said ...the program would go through whatever code I had, then once it had been 5 seconds....
    – Peter
    Commented Sep 4, 2019 at 10:19
29

Here is a simple example compatible with APScheduler 3.00+:

# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()

def some_job():
    print('Every 10 seconds')

# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()

...

sched.shutdown()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

import time
from threading import Event, Thread

class RepeatedTimer:

    """Repeat `function` every `interval` seconds."""

    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start = time.time()
        self.event = Event()
        self.thread = Thread(target=self._target)
        self.thread.start()

    def _target(self):
        while not self.event.wait(self._time):
            self.function(*self.args, **self.kwargs)

    @property
    def _time(self):
        return self.interval - ((time.time() - self.start) % self.interval)

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


# start timer
timer = RepeatedTimer(10, print, 'Hello world')

# stop timer
timer.stop()
1
  • Your second suggestion is the best threading-based answer IMHO: uses a single thread, does not drift (down to time imperfections?), allows to change parameters on the fly, very readable. You could actually inherit from threading.Thread directly and maybe override the run method instead? It would make your implementation very close to the threading.Timer implementation: github.com/python/cpython/blob/main/Lib/threading.py
    – C.J
    Commented Nov 8, 2024 at 11:34
13

Here's a version that doesn't create a new thread every n seconds:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

The event is used to stop the repetitions:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

See Improve current implementation of a setInterval python

4
  • It's worth noting that while this does allow something else to run while waiting for func to run again, this solution does not account for how long it takes func itself to run. So this solution waits n seconds between runs, as opposed to running every n seconds. Other solutions above at least come much closer to running every n seconds, though this solution has its advantages too.
    – Mike
    Commented Feb 13, 2018 at 20:38
  • @Mike: yes. If you follow the link; you see that it is mentioned explicitly and the corresponding solution is suggested. It depends on a specific case what solution is preferable.
    – jfs
    Commented Feb 13, 2018 at 21:04
  • it would be very nice if you could explain if the print function is called in the main thread. If yes, would the do something else code be run in another thread? Commented Feb 5, 2019 at 12:01
  • 1
    @toing_toing look at the code: "print" function is passed as "func" parameter to "call_repeatedly". "func" is called inside "loop" that is executed in another thread (look at Thread(target=loop)). In short: no, "print" function is not called in the main thread here.
    – jfs
    Commented Feb 5, 2019 at 14:32
1

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

Not the answer you're looking for? Browse other questions tagged or ask your own question.