schedule module conundrum - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: schedule module conundrum (/thread-18718.html) Pages:
1
2
|
RE: schedule module conundrum - Gribouillis - May-29-2019 I don't know why you can't do it with threading. Here is my code. It reads the sensor every second and warns if the threshold is reached. It also prints a temperature report every 5 seconds (python 3.5 code). It also does all this while waiting for user input to exit gracefully and potentially do other actions. import datetime as dt import random import sys from threading import Thread, Event monitor_event = Event() PROMPT = 'Type quit to quit: ' def print_msg(msg): print() print(msg) print(PROMPT, end='') sys.stdout.flush() def read_temperature(): temp = random.gauss(30, 7) # print('reading', temp) return temp class Monitor(Thread): def __init__(self, delta_sensor, delta_report, threshold): Thread.__init__(self) self.ds = delta_sensor.total_seconds() self.delta_report = delta_report self.threshold = threshold def run(self): # self.resume = True self.next_report = dt.datetime.now() + self.delta_report while True: monitor_event.clear() monitor_event.wait(timeout=self.ds) if monitor_event.is_set(): break temp = read_temperature() if temp > self.threshold: print_msg( 'Warning: temperature {:.1f} above threshold {:.1f}'.format( temp, self.threshold)) t = dt.datetime.now() if t >= self.next_report: print_msg( '{:%Y-%m-%d %H:%M:%S}: current temperature is {:.1f}'.format( t, temp)) self.next_report = t + self.delta_report if __name__ == "__main__": monitor = Monitor(dt.timedelta(seconds=1), dt.timedelta(seconds=5), 40) monitor.start() try: while True: s = input(PROMPT) if s.strip().lower() in ('q', 'quit'): break finally: monitor_event.set() monitor.join()
RE: schedule module conundrum - wgovideo - May-29-2019 Your expertise is amazing. You gave me a different approach to the problem. Thank you very much for the code example. And, thanks again for your help and patience. Grateful.. If I say the word python around here, people think I'm going to the zoo. |