Y
Y
Yoshinon Eared2017-10-26 03:10:43
Python
Yoshinon Eared, 2017-10-26 03:10:43

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

He works(!!!). But it doesn't seem transparent enough... for example, it doesn't come up with a sensible idea of ​​how the countdown is calculated down to seconds, before events occur. It also cannot display a list of what is already overdue in time.
In general, the code clearly smells like a crutch ... I wonder how you can make it better?
The main task is to call the condition on time, which is predetermined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dugin, 2017-10-26
@Aquinary

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()

S
Stalker_RED, 2017-10-26
@Stalker_RED

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?
The question in the title is really weird. He works because he can. There are no syntax errors, the logic is also ok, and the compiler does not swear at bad style. Perhaps some linter will swear, but you need to specifically ask him about it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question