Search code examples
pythonmysqlcronpymysql

Why would a program work well if activated manually but not as a daemon using crontab, mysql and python?


We have this code, of which the purpose is simply to publish in the database in MySQLWorkbench:

import pymysql.cursors
import os, time
import datetime

#Conexion a la base de datos
conn = pymysql.connect(‘example.example.us-west-2.rds.amazonaws.com', user= ‘xxxx', port= xxxx,     passwd = ‘xxxxx', db=‘xxxx')

def query():
    fecha = (str) (datetime.datetime.now())
    nfecha = fecha.split(' ')
    dia = nfecha[0]
    hora = nfecha[1]
    tabla='notificaciones'
    idcliente='1'
    notificacion='hola'
    tipo='saludo'
    with conn.cursor() as cursor:
        cursor.execute('insert into notificaciones(idcliente, notificacion, tipo, fecha, hora)     values(%s, %s, %s, %s, %s)', (idcliente, notificacion, tipo, dia, hora))
        conn.commit()

    print('success')


def main():
    query()

main()

When executed manually in the console, the code works great, however, when we want to set it as daemon, using crontab, it doesn't do anything.

In crontab tried this way:

sudo su
crontab -e
@reboot sudo python /home/pi/Desktop/DataBase.py

I've tried calling it from another program and already as an individual program. It doesn't work at all.

Help.


Solution

  • The solution for this case was: the program needed internet connection, then it needed some time before starting to give enough time so the OS comes up and the internet connection is established. It was solved adding a timer or sleep to the program in order to have the internet connection first.