Close

Scheduling and multi-thread in Python

A project log for MQTT Porchlight is an Intranet of Thing

Controlling a Wemo light switch with MQTT and Raspberry Pi

Mike SzczysMike Szczys 12/09/2019 at 21:020 Comments

Since my original goal is to replace the automatic scheduling for turning the porchlight on and off I need to write that into the Python file.

Why? Well, MQTT is just for transferring messages. So you can send "On" to my client script and it will turn the Wemo switch on. You can send "Status" and it'll report back with the status. But something needs to automatically watch for the schedule times and react when they come along.

In Python, the "schedule" package does this for you. Set a time, a function to call, and any repeat paramaters (like do this every day) and it'll manage the schedule, needing only for a function to be called checking for pending operations.

import schedule
import time
schedule.every().day.at("23:00").do(porchlight.off)
while(True):
    schedule.run_pending()
    time.sleep(60)

Threading

The problem with running the MQTT and schedule in the same Python script is that both need to be services. Luckily the MQTT package has threading built in, so calling a loop start (instead of a loop forever) will spin it off into its own thread and it won't interfere with the while loop above.

client.loop_start()

Discussions