-1

I have a method that count changes of some domains that I monitor, I need the method to run only once a day so that it counts the changes only once a day. I can't find good implementation for timer on python. Any suggestions?

  def count_changes(self):
    stamp = datetime.now()
    upper_limit = stamp - timedelta(days=7)
    lower_limit = stamp - timedelta(days=2)

    nameservers = models.NameServer.query.all()
    nameservers = [item.name for item in nameservers]
    domains = models.Domain.query.all()
    domains = [item.name for item in domains]
    changes = []
    upper_limit_changes = []
    lower_limit_changes = []

    for ns in nameservers:

        for domain in domains:
            scans = models.Scan.query.filter_by(nameserver=ns, 
            domain=domain).all()
            upper_limit_changes.extend(self.get_changes(scans, upper_limit))
            lower_limit_changes.extend(self.get_changes(scans, lower_limit))

    return upper_limit_changes, lower_limit_changes
davidism
  • 121,510
  • 29
  • 395
  • 339
Mindan
  • 979
  • 6
  • 17
  • 37

1 Answers1

1

There are multiple ways of doing it, some of them documented on this question. Although there is an accepted answer, I would recommend trying the one that uses the library schedule (pip install schedule). The code looks like this:

import schedule
import time

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute
  • Thanks I will try that, but can you please write where "this question" link suppose to go? – Mindan Dec 30 '17 at 06:05
  • Fixed the link. If you found this response useful please upvote it and mark it as answered ;) – Fernando Irarrázaval G Dec 30 '17 at 06:09
  • i'm a bit confused, how do I call get the timer on to execute my method at the given time? I'm both new to python and to timer. I use Python 3 – Mindan Dec 30 '17 at 06:42
  • The python program must be running a loop (the *while True:*) that checks if it is time to run a job. For the method to be executed you have to have executed the line *schedule.every().day.at("01:00").do(job,'It is 01:00')* once before. That line is saying that every day at 1am it should run the method job. – Fernando Irarrázaval G Jan 02 '18 at 02:07