Terminate thread and/or scheduler

Viewed 47

I'm more or less a Python beginner, so I might be using the wrong tools for the job. Or maybe I'm using the correct tools but not correctly.

Here's what I'm trying to do.

def stand_by(self, evt_time, number):
"""Waiting for scheduled time
Starts a scheduler in a separate thread that will run in the background
until a specific time is reached, usually a time in a flight's
schedule. Once that specific time is reached, the program will regularly
check if the state of the flight has changed as expected.
        
Args:
evt_time (:obj:`datetime`): The scheduled time of the status change.
Schedulers need Unix timestamps, so this has to be converted
inside the function.
number (str): Flight number of the flight that should be observed.
This function itself does not need it but it has to be passed on
as an argument.
"""
    # evt_time is given in UTC time but needs to be checked against
    # system time
    scheduler = sched.scheduler(time.time, time.sleep)
    tz = pytz.timezone(player.tz)

    # Turns the event time from datetime UTC into datetime player actual
    evt_time = pytz.utc.localize(evt_time).astimezone(tz)

    # Turns the datetime object into a UNIX time stamp
    evt_time = evt_time.timestamp()

    threading.Thread(target=lambda: scheduler.enterabs(
        evt_time, 2, check_dep, [number])).start()
    scheduler.run()

The user selects a flight they want to "board". Let's say it's 1 PM and the flight is scheduled to leave at 2 PM. The program will start a scheduler that later starts a "listener" at 2 PM to see if the flight has departed. To enable the user to continue using the program until 2 PM, the scheduler is running in a separate thread. I'm trying to figure out how I can terminate that thread and/or scheduler if the user decides to choose a different "flight" before 2 PM. I can't seem to find an elegant way of terminating threads.
I have found threading.timer, which can be cancelled, but that takes a time interval, not a time object...

I'm not married at all to this function. What I need is a way to run another function at a fixed time so that the program remains usable and that can be terminated if the user changes their mind. Thanks a lot for ideas!

0 Answers
Related