user781486 user781486 - 1 month ago 10
Python Question

Change this timer function to accept argument

I have this working timer function in python ver3.6 which runs at an interval of 2 seconds.

def timer_function_working():
threading.Timer(2, timer_function_working).start()
print ("stackoverflow")


I want this timer_function to accept the time interval as an argument. Here is the new code;

def timer_function(interval_sec):
threading.Timer(interval_sec, timer_function).start()
print ("stackoverflow")


However, I get this error message;

TypeError: timer_function() missing 1 required positional argument: 'interval_sec'

How do I change this timer function to accept argument?

Answer Source

According to the docs for threading.Timer, the first argument to Timer is interval

class threading.Timer(interval, function, args=[], kwargs={})

In your second code block, the first execution runs without issue because you've provided a value for interval. However, when the function is invoked at the end of the Timer's duration, you don't pass any arguments to the function itself, which leads to the error:

TypeError: timer_function() takes exactly 1 argument (0 given)

You can pass an argument to the function that Timer invokes upon completion in the following way:

import threading

def timer_function(interval_sec):
    threading.Timer(interval_sec, timer_function, args=[interval_sec]).start()
    print ("stackoverflow")


Alternatively, you can use a closure to bind the value interval_sec to another function, defined within timer_function that can be called without any arguments:

def timer_function(interval_sec):
    def inner_function():
        return timer_function(interval_sec)
    threading.Timer(interval_sec, inner_function).start()
    print ("stackoverflow")