tingbot / tingbot-python

🔩 Python APIs to write apps for Tingbot
Other
18 stars 9 forks source link

Fixing RunLoop.run() method to correctly schedule next time #46

Closed yumedzi closed 7 years ago

yumedzi commented 7 years ago

The idea is to fix RunLoop.run() method to correctly schedule next time to run the processed timer. It should be based on the time of last run not a previous one. Currently because of we use start_time as the base time for this we are getting timer ran two times in the same period of time:

To get more understanding consider this example:

import time
from itertools import count
import tingbot
from tingbot import *

it = count(1)
global_time = time.time()

@every(seconds=5)
def loop():
    global global_time
    time_now = time.time()
    delta, global_time = time_now - global_time, time_now

    number = next(it)
    print "#{}, delta: {} seconds".format(number, round(delta))

tingbot.run()

This loop will generate the following output:

#1, delta: 0.0 seconds                                                                                      
#2, delta: 5.0 seconds                                                                                      
#3, delta: 0.0 seconds                                                                                      
#4, delta: 5.0 seconds                                                                                      
#5, delta: 0.0 seconds                                                                                      
#6, delta: 5.0 seconds                                                                                      
#7, delta: 0.0 seconds   

showing that loop will be fired two times after 5 seconds each time. The same behaviour for minutes and multiple scheduled timers.

joerick commented 7 years ago

Yep you're right. I didn't pick this up in development since I normally have a fast-running timer doing drawing, and then slow timers doing background updates etc.

BTW: 👌 a perfect pull request! One line change, accompanied with a well reasoned explanation and sample code!

joerick commented 7 years ago

FYI, I made a few more changes after this - one was to change this scheduling behaviour slightly, so that delays in any timers didn't affect the scheduling too much. See 9a172376d7147e9024cac74d0d9ef92ced436f06.

joerick commented 7 years ago

Released as tingbot-python v1.0.0 on PyPI. Will be in the next version of Tide.