简体   繁体   中英

Run function at a specific time in python - TypeError

I want to schedule a function to run at a specific point in time using the built in python library sched

I've been looking at the code from the answer to Run function at a specific time in python .

The problem's that when I run the code from the answer I get a TypeError . Why?

Thanks!

import sched, time

def action():
    print('Hello world')

s = sched.scheduler(time.localtime, time.sleep)
s.enterabs(time.strptime('Fri Oct 22 17:20:00 2021'), 0, action)
s.run()

# ERROR
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time' 

You are receiving a TypeError because there is no built-in subtraction method for time.struct_time objects. Both the time.localtime() and time.strptime() functions return a time.struct_time object. In other words, sched.scheduler cannot determine the difference in time (how long to delay) between the current time and the time that you specified. More information about the time.struct_time object can be found here .

If you modify your code to something similar to the following, it will work.

import sched, time

def action():
    print('Hello world')

s = sched.scheduler(time.time, time.sleep)
s.enterabs(time.mktime(time.strptime('Sun Oct 24 21:05:00 2021')), 0, action)
s.run()

The time.mktime() function allows for the conversion of time.struct_time objects to a floating point value. From the documentation , it seems like this was specifically added so it can be utilized with time.time() which also returns a floating point value. By instructing the scheduler to utilize the time.time function in conjunction with the time.mktime function, it allows for the subtraction of floating point values which eliminates the TypeError. That difference is then passed to the delay function (time.sleep in your script) for the delaying of the task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM