简体   繁体   中英

Python pause thread, do manually and reset time

I need to call function every x seconds but with option to call it manually and in this case reset time. I have sth like this:

import time
import threading

def printer():
    print("do it in thread")

def do_sth(event):
    while not event.is_set():
        printer()
        time.sleep(10)

event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
t.daemon = True
t.start()
a = input()
if a == 't':
    event.set()
elif a == 'm':
    event.wait()
    printer()
    event.clear()

UPDATE: I have found something that helped me a lot: Python - Thread that I can pause and resume Now my code look like this:

import threading, time, sys

class ThreadClass(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.can_run = threading.Event()
        self.thing_done = threading.Event()
        self.thing_done.set()
        self.can_run.set()

    def run(self):
        while True:
            self.can_run.wait()
            try:
                self.thing_done.clear()
                self.do_in_thread()
            finally:
                self.thing_done.set()
            time.sleep(5)

    def pause(self):
        self.can_run.clear()
        self.thing_done.wait()

    def resume(self):
        self.can_run.set()

    def do_in_thread(self):
        print("Thread...1")
        time.sleep(2)
        print("Thread...2")
        time.sleep(2)
        print("Thread...3")


def do_in_main():
    print("Main...1")
    time.sleep(2)
    print("Main...2")
    time.sleep(2)
    print("Main...3")

if __name__ == '__main__':

    t = ThreadClass()
    t.daemon = True
    t.start()
    while True:
        i = input()
        if i == 'm':
            t.pause()
            do_in_main()
            t.resume()
        elif i == 't':
            sys.exit()
            # t.join()

The only problem is that when I terminate, a would like thread to finish its job before it exits.

It may be that buffered outputs are the culprits and thus - you're are getting your expected behaviour.

I changed your code to the following, and it seems to do something (if that's what you wanted, is up to you):

import time
import threading

def printer():
    print("do it in thread")

def do_sth(event):
    print("event.is_set:", event.is_set())
    while not event.is_set():
        printer()
        time.sleep(10)

event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
print("t:",t)
t.daemon = True
t.start()
a = input()
if a == 't':
    event.set()
elif a == 'm':
    event.wait()
    printer()
    event.clear()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM