2

I want to repeat a function at timed intervals. The issue I have is that the function runs another function in a separate thread and therefore doesn't seem to be working with my code.

From the example below, I want to repeat function1 every 60 seconds:

from multiprocessing import Process
from threading import Event

def function2(type):
    print("Function2")

def function1():
    print("Function1")
    if __name__ == '__main__':
        p = Process(target=function2, args=('type',))
        p.daemon = True
        p.start()
        p.join()

function1()

To repeat the function I attempted to use the following code:

class TimedThread(Thread):
    def __init__(self, event, wait_time, tasks):
        Thread.__init__(self)
        self.stopped = event
        self.wait_time = wait_time
        self.tasks = tasks

    def run(self):
        while not self.stopped.wait(0.5):
            self.tasks()

stopFlag = Event()
thread = TimedThread(stopFlag, 60, function1)
thread.start()

Both snippets combined print "Function1" in a timed loop but also produce the following error:

AttributeError: Can't get attribute 'function2' on <module '__main__' (built-in)

Any help would be greatly appreciated.

Calum
  • 104
  • 11

3 Answers3

0

You can wrap your function1, like:

def main():
    while True:
        time.sleep(60)
        function1()

or you can have it run in a separate thread:

def main():
    while True:
        time.sleep(60)
        t = threading.Thread(target=function1)
        t.start()
Matej
  • 932
  • 4
  • 14
  • 22
0

It actually works for me, printing Function1 and Function2 over and over. Are these two snippets in the same file?

If you import function1 from a different module, then the if __name__ == '__main__' check will fail.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Within the same file, "Function1" prints in a loop but I get the following error : `AttributeError: Can't get attribute 'function2' on – Calum Jan 14 '18 at 21:47
0

I managed to find an alternative, working solution. Instead of using processes, I achieved the desired results using threads.The differences between the two are well explained here.

from threading import Event, Thread

    class TimedThread(Thread):
        def __init__(self, event, wait_time):
            Thread.__init__(self)
            self.stopped = event
            self.wait_time = wait_time

        def run(self):
            while not self.stopped.wait(self.wait_time):
                self.function1()

        def function2(self):
            print("Function2 started from thread")
            # Do something

        def function1(self):
            print("Function1 started from thread")
            # Do something
            temp_thread = Thread(target=self.function2)
            temp_thread.start()

    stopFlag = Event()
    thread = TimedThread(stopFlag, 60)
    thread.start()
Calum
  • 104
  • 11