I have the following problem. I want a function to be called at a specific time e.g. 8 a.m. and another function to be called at another time e.g. 2 p.m. Is there a way to make it with some kind of eventhandler or something or do I have to use threads? Just time.sleep would be hard because there will be more functions at other times.
Asked
Active
Viewed 181 times
-1
-
can you run the script continously over days ? – dallonsi Jun 06 '19 at 13:41
-
That's the plan I want kind of a server that executes different functions at different times – Dani Jun 06 '19 at 13:43
-
2Have you tried to execute your functions as CRON jobs? – Kshitij Saxena Jun 06 '19 at 13:43
-
Haven't heard of I'll Google it but I just read it is for Unix systems isn't there a way to do it with python code? :) – Dani Jun 06 '19 at 13:46
-
2A scheduler is always available on any decent platform nowadays. You have cron under Linux and Unix, the Task Scheduler under Windows. They are certainly more robust and more extensively tested than what you could build. Are you sure you really want to roll your own? If yes, just try to mimic a Unix cron, because it is simpler than the Windows version. – Serge Ballesta Jun 06 '19 at 13:49
-
2There's a python module for that called ["schedule"](https://pypi.org/project/schedule/) – Darkonaut Jun 06 '19 at 13:50
-
another option apart from OS scheduler and `schedule` package is [advanced python scheduler](https://apscheduler.readthedocs.io/en/latest/) – buran Jun 06 '19 at 13:52
-
Thanks I'll try the schedule module :) – Dani Jun 06 '19 at 13:56
1 Answers
0
from datetime import datetime
while True:
d = datetime.now().time()
if d.hour == 8:
function_1()
if d.hour == 14:
function_2()

dallonsi
- 1,299
- 1
- 8
- 29
-
Thanks! I think I'll make it similar with a list so I can add functions :) – Dani Jun 06 '19 at 13:48
-
1Keep in mind that, at 8 am, this code will execute many times function_1() (until it's 9 !) – dallonsi Jun 06 '19 at 13:50
-
1Don't use a ``while True`` to wait! That wastes a lot of CPU time. – MisterMiyagi Jun 06 '19 at 13:50
-
1well, you realise it will execute respective function continuously for an hour, right? – buran Jun 06 '19 at 13:50
-
-
1I'd make it also test on minute and then add a time.sleep to make sure the minute has passed and also wait 60 sec after every loop, so the GPU is not so exhausted and the functions get called only one time every day – Dani Jun 06 '19 at 13:54