Sorin Burghiu
Sorin Burghiu

Reputation: 779

How to add an event to a running thread?

I am trying to set an alarm using sched and thread. If I run create_alarm() once, I can create one alarm. But if I run the same function again it will say that threading has already started.

Is there a way to run the function create_alarm() more than once and having multiple alarms in the thread simultaneously.

import sched, time, threading, datetime

s = sched.scheduler(time.time, time.sleep)
t = threading.Thread(target=s.run)

def trigger_alarm(name):
    print("Alarm has triggered! Alarm name: ", name)
    print("The time is now: {}".format(datetime.datetime.now()))

def create_alarm():
    alarmName = input("What is your alarm name?")
    alarmTime = input("When would you like your alarm to trigger (Format: YYYY-MM-DD HH:MM:SS)")
    setAlarm = time.strptime(alarmTime, '%Y-%m-%d %H:%M:%S')
    setAlarm = time.mktime(setAlarm)
    globals()[alarmName] = s.enterabs(setAlarm,1,trigger_alarm,(alarmName,))
    t.start()
    print("Your alarm has been set.")

Upvotes: 1

Views: 73

Answers (1)

rgov
rgov

Reputation: 4329

Each time you call create_alarm, it will run t.start(). A thread can only be started once, so it will fail on the second call.

You could call t.start() after you create the thread instead of inside this function, or you could test if t is already running before you call t.start().

Upvotes: 1

Related Questions