0

I would like to run this script like a automatic service who will run every minute, everyday with Twisted (I first tried to 'DAEMON' but it seems to difficult and i didn't find good tutos to do it, I already tried crontab but that's not what I'm looking for).

Do anyone ever do that with Twisted because I'm not finding the tutorial made for my kind of script(getting datas from a db table and putting them in another table of same db) ? I have to keep the logs in a file but it will not be the most difficult part.

    from twisted.enterprise import adbapi
from twisted.internet import task
import logging
from datetime import datetime
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks


"""
Test DB : This File do database connection and basic operation.
"""

log = logging.getLogger("Test DB")

dbpool = adbapi.ConnectionPool("MySQLdb",db="xxxx",user="guza",passwd="vQsx7gbblal8aiICbTKP",host="192.168.15.01")


class MetersCount():

    def getTime(self):
        log.info("Get Current Time from System.")
        time = str(datetime.now()).split('.')[0]
        return time

    def getTotalMeters(self):
        log.info("Select operation in Database.")
        getMetersQuery = """ SELECT count(met_id) as totalMeters FROM meters WHERE DATE(met_last_heard) = DATE(NOW()) """

        return dbpool.runQuery(getMetersQuery).addCallback(self.getResult)

    def getResult(self, result):
        print ("Receive Result : ")
        print (result)
        # general purpose method to receive result from defer.
        return result

    def insertMetersCount(self, meters_count):
        log.info("Insert operation in Database.")
        insertMetersQuery = """ INSERT INTO meter_count (mec_datetime, mec_count)  VALUES (NOW(), %s)"""
        return dbpool.runQuery(insertMetersQuery, [meters_count])

    def checkDB(self):
        d = self.getTotalMeters()
        d.addCallback(self.insertMetersCount)
        return d

a= MetersCount()
a.checkDB()
reactor.run()
  • Hello again. There is ample Twisted documentation for this. Did you read any of it? – Jean-Paul Calderone May 03 '19 at 16:12
  • Yes, I have already red a lot of documentation about twisted but I don't really know how can I use it in my case I saw a lot of examples but it was for "simple" scripts. If you have some documentation which could really help me, thanks for sharing. –  May 04 '19 at 18:27

1 Answers1

0

If you want to run a function once a minute, have a look at LoopingCall. It takes a function, and runs it at intervals unless told to stop.

You would use it something like this (which I haven't tested):

from twisted.internet.task import LoopingCall
looper = LoopingCall(a.checkDB)
looper.start(60)

The documentation is at the link.

Peter Westlake
  • 4,894
  • 1
  • 26
  • 35