0

my goal is very simple: starting a periodicCallback at a specific time. I tried to look everywhere but all the examples read are related to a timedelta of the current time and not to a defined time.

I write a simple example.

import tornado.ioloop
import datetime
from datetime import date, time
from tornado.ioloop import IOLoop, PeriodicCallback

def startService():
    print("periodic thing")


def periodicCallback():
    periodic = PeriodicCallback(callback=startService,callback_time=5000)
    periodic.start()

if __name__ == "__main__":
    main_loop = IOLoop.instance()
    # I want to set a specific time
    starting_time = time(14, 30, 00)
    # After this time i would want to have the message "periodic thing" every callback_time
    (...)
    #my first test but i have error about deadline unsupported:
    IOLoop.current().add_timeout(starting_time, periodicCallback)
    main_loop.start()

thanks for help

1 Answers1

0

The error - Unsupported deadline - you're seeing is because add_timeout takes a datetime.timedelta object, whereas, you're giving it a datetime.time object.

Since, you want to run the callback at a specific time, you can calculate the timedelta upto that time.

import datetime

# see the current time
now = datetime.datetime.now()

# create a datetime object for your desired time
starting_time = datetime.datetime(year=2018, month=3, day=13, 
                                  hour=14, minute=30) 

# subtract `now` from `starting_time`
# to calculate timedelta
td = starting_time - now

main_loop.add_timeout(td, periodicCallback)

If the year or month or day are same as the now time, you can also do:

starting_time = datetime.datetime(year=now.year, month=now.month, day=now.day, 
                                  hour=14, minute=30)   
xyres
  • 20,487
  • 3
  • 56
  • 85
  • Thanks, i'll try it :) – Luca Palombella Mar 15 '18 at 09:10
  • I have another question: if startService() makes something asyncronous so it becomes: @gen.coroutine def startService(): yield do_coroutine() how can i check if his time is no longer of callback_time of periodicCallback()? (for example 10 seconds > 5 seconds...) Is there a method to wait if periodicCallback is ended or pass to next schedule? thanks – Luca Palombella Mar 19 '18 at 16:47