WeInThis
WeInThis

Reputation: 547

Python - Whats the best way to run a method/function based on Time. (24h)

I have been thinking to run a script/code on a time that I want. Like we say etc. I want to run a program at 00:00 (I enter it in the code that I want to start at that time) meanwhile it's 23:21. So it should wait until that time and then run the method/function or whatever it should do.

What would be in that case the best way to run something like this in that case :) ?

EDIT: Exemple -

I was thinking like to do it through a code. Like etc. I have a code with we say 3 functions. At the time 23:50 I want function nr 1 to run. Then at 23:55 i want the function nr 2 to run and then 00:05 i want the function nr3 to run and all that in the same py file.

Upvotes: 0

Views: 112

Answers (4)

sametcodes
sametcodes

Reputation: 553

You can use crontab.

To edit:

crontab -e

To add initial time:

50 23 * * * /usr/bin/python /your/file.py function1
55 23 * * * /usr/bin/python /your/file.py function2
05 00 * * * /usr/bin/python /your/file.py function3

And it should be like this your file.

import sys

def function1():
    print "function 1 running"
def function2():
    print "function 2 running"
def function3():
    print "function 3 running"

if sys.argv[1]:
    run = sys.argv[1]
    if run == "function1":
      function1()
    elif run == "function2":
       function2()
    elif run == "function3":
       function3()

Upvotes: 2

Błotosmętek
Błotosmętek

Reputation: 12927

You can do something like this:

import time
starttimes = { (23, 50): func1, (23, 55): func2, (0, 5): func3 }

while True:
    now = tuple(time.gmtime()[3:5])
    if now in starttimes:
        starttimes[now]() # call a function 
    time.sleep(60)

Mind that it is a very crude solution, assuming in particular that none of func1func3 functions will run for longer time than the period left to the starting time of the next function. Also: you need to start your program and leave it running all the time. You kill it (or reboot your system), you need to start it again.

Upvotes: 1

Yaroslav Surzhikov
Yaroslav Surzhikov

Reputation: 1608

sched library is what you are looking for. No site-packages or another utilities like cron are required.

Upvotes: 1

DhruvPathak
DhruvPathak

Reputation: 43235

You are looking for a dedicated task scheduler like Celery.

Or to do it simply, you can put a crontab to run a python script to run every minute. Store method name and time to run in a database. When the task runs, it sees if there is any task to be run for the minute,and executes the method specified in the database.

Upvotes: 0

Related Questions