-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
2
  • Hi, have you tried bash cron? Or there is a particular reason that you want to schedule it from the code? Commented Dec 30, 2017 at 5:49
  • I have to make the method run once every day and I need that to be done from code Commented Dec 30, 2017 at 5:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks I will try that, but can you please write where "this question" link suppose to go?
Fixed the link. If you found this response useful please upvote it and mark it as answered ;)
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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.