这个问题在这里已有答案:
我有一个计算我监控的某些域的更改的方法,我需要每天只运行一次的方法,以便它每天只计算一次更改。我在python上找不到计时器的好实现。有什么建议?
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
有多种方法可以做到这一点,其中一些记录在this question上。虽然有一个公认的答案,但我建议尝试使用库schedule(pip安装计划)。代码如下所示:
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