PYTHON - Create sub-function to monitor main function execution and restart if needed

Asked

Viewed 24 times

0

The following function runs 24 hours a day (every 35 minutes on average), exporting information and clicking on a given system.

The problem is that sometimes the fault occurs and the code does not respond. The loop keeps running on the error.

My need was to create a solution that ran in parallel, monitoring and restarting the execution of the function def main_robo(), if it did not generate a response after 35 minutes.

def main_robo():

contador = 1
contador_programa = 0

while True:

    dir_path = os.path.dirname(os.path.realpath(__file__))
    login = open(dir_path + "\\login.txt", "r")
    login = login.readlines()

    contador_programa = contador_programa + 1

    print('===============================', 'Execução da tarefa: ', contador_programa, '===============================')

    inicio = datetime.now().strftime('%d-%m-%Y %H:%M:%S')

    msg_1 = str(login[2]) + ": Iniciando importação!"
    telegram_bot_sendtext(emojize(":robot_face::smile:", use_aliases=True) + msg_1)

    if contador == 1:
        retorno = executar_e()

        if retorno == 'Processado_e':
            retorno = executar_g()

    if contador == 2:
        retorno = executar_e_check()

        if retorno == 'Processado_e':
            retorno = executar_g()

    if contador == 3:
        retorno = executar_g()

    fim = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
    total_time = (datetime.strptime(fim, '%d-%m-%Y %H:%M:%S') - datetime.strptime(inicio, '%d-%m-%Y %H:%M:%S'))

    print('#############', 'Status de execução da tarefa: ', retorno + ' em ' + str(total_time), '#############')

    if retorno == 'Processado_g':

        contador = 1
        msg_2 = str(login[2]) + ": Importação realizada: " + str(total_time)
        telegram_bot_sendtext(emojize(":robot_face::sunglasses:", use_aliases=True) + msg_2)

    if retorno == 'Erro_e':

        contador = 2
        msg_3 = str(login[2]) + ": Erro na importação!"
        telegram_bot_sendtext(emojize(":robot_face::face_with_head-bandage:", use_aliases=True) + msg_3)

    if retorno == 'Erro_g':

        contador = 3
        msg_3 = str(login[2]) + ": Erro na importação!"
        telegram_bot_sendtext(emojize(":robot_face::face_with_head-bandage:", use_aliases=True) + msg_3)


fim = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
total_time = (datetime.strptime(fim, '%d-%m-%Y %H:%M:%S') - datetime.strptime(inicio, '%d-%m-%Y %H:%M:%S'))
  • Hello Rafael, it would be more correct to use if, Elif in the logic of your conditions, so if a condition has been accepted, it does not need to go through all the others.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.