5

so i have this python app and i need to schedule tasks on specific datetimes.

I was thinking something like:

    scheduler.add(datetime,func())

which would call function func at the specified date and time but accurately. I want seconds or even milliseconds accuracy.

I searched and found the "scheduler" module and tried it but you can only use it with hh:mm format instead of hh:mm:ss.

I hope i am clear

jino dav
  • 51
  • 2
  • 5

2 Answers2

4

The sched module from the standard library uses time.time by default, which has pretty good precision*. It has a similar API to the one you're describing:

import sched
from datetime import datetime

s = sched.scheduler()
s.enterabs(datetime(2018, 1, 1, 12, 20, 59, 0).timestamp(), 1, func)
s.enterabs(datetime(2018, 1, 1, 12, 20, 59, 500000).timestamp(), 1, func)
s.run()

This program will run func on 2018-01-01 at 12:20:59, then again half a second (500000 microseconds) later, then quit.

Of course, you can use any way of getting a timestamp, including parsing a datetime from a string and working from there, or just entering a timestamp directly.


*: On Linux and Mac, precision of time.time is around 1µs. On Windows, it is around 16ms. It is guaranteed to be at least 1 second.

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • 1
    I had to use s = sched.scheduler(time.time, time.sleep) for you code to work on my python distribution. Thanks for the help ! – Tobbey May 17 '18 at 13:51
0

Maybe in func, you should add time.sleep(s) to the start, so you can be accurate to the second. Also, when passing in a function, pass func not func(), as func() returns a value, and func is a function

paper man
  • 488
  • 5
  • 19