Running single python script with different crontab commands

103 views Asked by At

I'm trying to create a single python script that needs to run in a multiple instance continuously parallel to each other on the background.

I tried using crontab in ubuntu 20.04 and have the following

* * * * * python3 ~/Documents/xxx/pollingservice.py -d 185 > /tmp/log 2>&1

1 * * * * python3 ~/Documents/xxx/pollingservice.py -d 186 > ~/Documents/logs 2>&1

1 * * * * python3 ~/Documents/xxx/pollingservice.py -d 186 > ~/Documents/logs-186 2>&1

1 * * * * python3 ~/Documents/xxx/pollingservice.py -d 187 > ~/Documents/logs-187 2>&1

Basically I want to run this single script with multiple arguments. what they are doing is fetching data from device using a modbus protocol and save it in a csv file. However it seems like the cronjob is not running there isn't any log file being created after 1 minute of restarting the cron using the command service cron start

the following is the python script


from pymodbus.client.sync import ModbusTcpClient
from ast import literal_eval
import requests
import json
import time
import datetime
import csv
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--device", help="Device ID")
args = parser.parse_args()


def pollData(devices):
    items = []
    client = ModbusTcpClient(host=devices['ip_address'], port=devices['port'])
    connection = client.connect()
    alarm = "NO ALARM"

    for driver in devices['thresholds']['threshold_data']:
        try:

            address = literal_eval('0x0{}'.format(driver['hex_offset'].rstrip('H')) or 0)
            response = client.read_holding_registers(address, 10, unit=int(devices['slave_id']))

            converted = response.registers[0] / int(driver['register_scale'])
            bin8 = lambda x: ''.join(reversed([str((x >> i) & 1) for i in range(16)]))

            try:
                value = float(round(converted, 2))
                print(value)
                if float(converted) < float(driver['low_critical'] or 0):
                    alarm = "LOW CRITICAL"
                    print('LOW CRITICAL')
                elif float(driver['low_warning'] or 0) > float(converted) > float(driver['low_critical'] or 0):
                    alarm = "LOW WARNING"
                    print('LOW WARNING')
                elif value > float(driver['high_warning'] or 0):
                    alarm = "HIGH WARNING"
                    print('High Warning')
                elif value > float(driver['high_critical'] or 0):
                    alarm = "HIGH CRITICAL"
                    print('High Critical')

                sendData(devices['device_id'], value, alarm)

            except TypeError as e:
                print(e)

            timestamp = str(datetime.datetime.now())

            items.append(round(converted, 2))

            average = average_list(items)
            maximum_value = max(items)
            minimum_value = min(items)

            # Send data to threshold and save only every 15 minutes
            send_poll(devices['device_id'], round(converted, 2), driver['address'], minimum_value, maximum_value, average)

            with open('/home/xxx/Documents/csv' + csv_name, 'a+', newline='') as f:
                driver_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                driver_writer.writerow([timestamp,
                                        devices['device_id'],
                                        devices['slave_id'],
                                        driver['address'],
                                        round(converted, 2),
                                        alarm])


        except ValueError as e:
            print(e)
            continue

    return items


def sendData(device_id, alarm_value, alarm_status):
    r = requests.post('http://xxx/store-alarm', data={
        'device_id': device_id,
        'alarm_value': alarm_value,
        'alarm_status': alarm_status
    })


def send_poll(device_id, value, modbus_address, min_value, max_value, average_value):
    r = requests.post('http:/xxx', data={
        'device_id': device_id,
        'modbus_address': modbus_address,
        'value': value,
        'min_value': min_value,
        'max_value': max_value,
        'average_value': average_value,
    })

    print(r)

def average_list(lst):
    return sum(lst) / len(lst)



while True:

    try:
        devices = requests.get('http://xxxx'.format(str(args.device))).json()
        data = pollData(devices)

        time.sleep(3)
    except Exception as e:
        print(e)
        continue

is there anything i can do here to make them run parallel to each other? Thanks!

0

There are 0 answers