Answer the question
In order to leave comments, you need to log in
Why is this code working?
Good day to all!
There is this code:
while (1):
for iterator in range(len(posts)):
# Для прозрачности вычислений
time_post_a = datetime.now()
time_post_a = int(time.mktime(time_post_a.timetuple()))
time_post_b = posts[iterator]['time']
time_post_b = int(time.mktime(time_post_b.timetuple()))
# Выполнить действие, в случае, если "время пришло" по массиву posts
if ((time_post_a - time_post_b) == 0):
print ('Итератор: ' + str(iterator) + ', Новая публикация: ' + str(posts[iterator]['time']))
time.sleep(1) # Если его убрать, то начинаются дикие пляски
break
Answer the question
In order to leave comments, you need to log in
If there was a competition for writing the most crooked event scheduler (task scheduler) - this code would undoubtedly take first place) Try, for example, delayed calls in asyncio.
UPD An example of a simple head-on solution, without asynchrony:
from time import time, sleep
from operator import attrgetter
class Article:
def __init__(self, timestamp, text):
self.timestamp, self.text = timestamp, text
def post(self):
print(f"planned={self.timestamp:.0f}, posted={time():.0f}, text={self.text}")
class Scheduler:
def __init__(self, *articles):
self.articles = sorted(articles, key=attrgetter("timestamp"))
def execute(self):
for article in self.articles:
sleep(max(article.timestamp - time(), 0))
article.post()
if __name__ == "__main__":
now = time()
Scheduler(
Article(now + 7, "post3"),
Article(now + 2, "post1"),
Article(now + 3, "post2"),
).execute()
1. calculate the remaining time for all posts
2. find the minimum
3. time.sleep( what was calculated in step 2)
4. print ...
5. return to step 1
It also cannot display a list of what is already overdue.What do you even want to do?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question