简体   繁体   中英

How can I compare the current time with the next 10 seconds?

How can I compare the current time with the next 10 seconds?

eg in the current time, i post a message to mqtt broker, and then in next 10 secs automatically will post to mqtt broker again.

I did not quite understand your question. But I think you want to do something now and do it in the next 10 seconds. If that's what you want, then,

import time
print("Do something")
time.sleep(10)
print("Do something")

Or if you want it do continuously, then:

import time
i = 0
while i < 10: #Using while loop for readability
    print("Do something")
    i = i + 1 # You can use i += 1 or i++
    time.sleep(10)

If you don't want to use sleep , compare the current now with your starting time + 10 seconds. Inside the loop you can do pretty much whatever you want.

from datetime import datetime,timedelta


start_the_clock = datetime.now()
print ('now it is',start_the_clock)
end_the_clock = start_the_clock+timedelta(seconds=10)
print ('we will end at',end_the_clock)
ticker = r'\|/-'
t = 0
while datetime.now() < end_the_clock:
    print ('waiting... '+ticker[t & 3], end='\r')
    t += 1
print ('\nDone waiting at',datetime.now())

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