Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how do i accurately schedule one time tasks

Tags:

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

like image 330
jino dav Avatar asked Nov 18 '17 14:11

jino dav


1 Answers

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.

like image 196
Wander Nauta Avatar answered Sep 21 '22 12:09

Wander Nauta