-1

What is the proper way to call a method at a certain time (certain time here is a parameter)?

I need the timer, but is it necessary to represent incoming time and time.now() in seconds to get and to use the difference between them?

The code:

import datetime, time
import threading
from threading import Timer

def doItThen():
    print ("did it")

def launchTimer(dateAndTime):
    dateTimeNow = datetime.datetime.now()
    t = threading.Timer((dateAndTime-dateTimeNow).seconds, doItThen)
    t.start()

if __name__ == "__main__":

    launchTimer(datetime.datetime(2018, 2, 21, 8, 27, 51))

the result:

did it

(works)

but what are the risks in using this approach? im not good in testing or predicting the weeknesses

ndmeiri
  • 4,979
  • 12
  • 37
  • 45
Roman Kishmar
  • 37
  • 1
  • 2
  • 11

3 Answers3

2

Check out scheduler.enterabs from Python's Sched lib.

The enterabs function allows you to set a specific time to call a function. Here's a direct link.

The basic syntax is as follows:

scheduler.enterabs(time, priority, action, argument=(), kwargs={})
Gerik
  • 698
  • 3
  • 11
1

If I understand your question correctly, the module schedule might be what you are looking for.

How do I get a Cron like scheduler in Python?

import schedule
import time 
def job(): 
    print("I'm working...")     

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job) 
schedule.every().day.at("10:30").do(job) 
while 1: 
    schedule.run_pending()
    time.sleep(1)
gtalarico
  • 4,409
  • 1
  • 20
  • 42
0

use python schedule

schedule.every().day.at("10:10").do(job)

mirhossein
  • 682
  • 7
  • 16
  • 1
    I need to call a method at a random time. It's not periodic or predictable. – Roman Kishmar Feb 18 '18 at 08:11
  • explaint what exactly you are going to do by this. also you can make a random timestamps and pu it in a list like [1518942118,1518942125,...] then run it with schedule – mirhossein Feb 18 '18 at 08:22