I am new to programming and doing a simple academic project with Raspberry Pi, I have a script which will monitor the changes of database and output the change with 2 different color LED.

I want it to be executed everytime raspberry pi reboot and SSH is not logged in. Currently I have added the task in crontab but it's not executed when reboot. When I run in SSH command line, it works and when i logout PuTTY, it stop.

I have another script in crontab which working well when Pi reboot

My python script


import MySQLdb

import RPi.GPIO as GPIO
import time
GPIO.setup(38,GPIO.OUT) #red(away)
GPIO.setup(40,GPIO.OUT) #green(home)

while True:
    db = MySQLdb.connect(host="localhost", user="ssss", passwd="sssss"$

    #cursor for select
    cur = db.cursor()

    cur.execute("SELECT status FROM home_mode ORDER BY id DESC LIMIT 1")
    last_status = str(cur.fetchone())
    if last_status == "('HOME',)":
            GPIO.output(40, GPIO.HIGH)
            GPIO.output(38, GPIO.LOW)
    elif last_status == "('AWAY',)":
            GPIO.output(40, GPIO.LOW)
            GPIO.output(38, GPIO.HIGH)
            print "WRONG"


The coding maybe very poor because I am really new in python even programming. Hope anyone could give solution/advise, thank you.


2 Answers 2


A better choice would be to use systemd and its associated systemctl command.


You should use a systemd unit file to start the python script on boot up and run it as service. Just create a new service with:

rpi ~$ sudo systemctl --force --full edit monitor-db.service

In the empty editor insert these statements, save them and quit the editor:

Description=Monitor Database changes



Enable and check the new service with:

rpi ~$ sudo systemctl enable monitor-db.service
rpi ~$ systemctl status monitor-db.service


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.