Home > Back-end >  Use python to do a task on raspberry on a specific time
Use python to do a task on raspberry on a specific time

Time:06-14

I'm creating a smart charging program with Python and the ayncio library.

The program is running on a raspberry pi connected to a relay. I would want that for example at 4pm, the raspberry pi opens the relay and at 5pm it closes it.

For this I need a signal that is sent from the program but I don't know how to keep the program runing other tasks while it's charging and how can I keep checking the time (like every minute) so the program knows when to stop the charge.

I was thinking doing something like

import datetime

startCharging = datetime.datetime(year=2022, month=7, day=7, hour=16, minute=0)
stopCharging = datetime.datetime(year=2022, month=7, day=7, hour=17, minute=0)

if(datetime.datetime.now()==startCharging):
    # Start Charging
else:
    # Stop Charging 

But how could I run this function all the time without interrupting other functions?

CodePudding user response:

You could use the threading library. In the code below you create a thread for the charging function and you use a flag to stop (kill) the thread when the charging needs to end. This way you can send eventually new values and restart your thread without problems.

The flag is sent as lambda function to avoid using global variables.

import time
import datetime
import threading

startCharging = datetime.datetime(year=2022, month=6, day=13, hour=10, minute=26)
stopCharging = datetime.datetime(year=2022, month=6, day=13, hour=10, minute=28)

def charging(startCharging, stopCharging,flag):
    while True:
        if(datetime.datetime.now()>startCharging and datetime.datetime.now()< stopCharging ):
            # Start Charging
            print("Charging...")
            time.sleep(2)
        else:
            # Stop Charging 
            print("Not charging.")
            time.sleep(2)
        if flag():
            break


if __name__  == "__main__":
    flag = False
    charge = threading.Thread(target=charging, args=(startCharging, stopCharging,lambda:flag))
    charge.start()
    while True:
        print("Doing other stuff blabla")
        time.sleep(3)
        if datetime.datetime.now() >= stopCharging:
            flag = True
            charge.join()
            print('Tasks finished')
        
  • Related