Home > Software engineering >  Timer *args, **kwargs in while gets null after first iteration
Timer *args, **kwargs in while gets null after first iteration

Time:05-24

I've done a repeating timer that doesn't work, the first iteration works but then it says args and kwargs is NoneType even though it worked the first time:

'NoneType' object is not callable

The timer.py:

from threading import Timer

class repeat_timer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            try:
                self.function(*self.args, **self.kwargs)
            except Exception as e:
                print("______EXCEPTION IN TIMER_______")
                print(e)

This is how i call it:

from timer import repeat_timer

timer = repeat_timer(delay, process_multiple_files(filter_json_path))
timer.run()

The delay is just an int with amount of seconds between each run. process_multiple_files(filter_json_path) is a function to check files and upload to a db. filter_json_path is a string with a path to a json file

I dont know where to start since it works perfect the first time but not the second time?

To clarify the timer works and it tries to run the code within each X seconds of delay The problem is when self.function(*self.args, **self.kwargs) is run and gives the exception 'NoneType' object is not callable the second time of the ireation, so the first run is all fine and dandy but after that it runs but gets an exception as said above.

CodePudding user response:

You need to call it like this:

from timer import repeat_timer

timer = repeat_timer(delay, process_multiple_files, filter_json_path)
timer.run()

process_multiple_files is the function you want the timer to call, and filter_json_path is the arg it should pass when in makes the call

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

class threading.Timer(interval, function, args=None, kwargs=None)
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.

  • Related