import timefrom itertools import count
def buzzergen(period):nexttime = time.time() + periodfor i in count():now = time.time()tosleep = nexttime - nowif tosleep > 0:time.sleep(tosleep)nexttime += periodelse:nexttime = now + periodyield i, nexttime
调用常规buzzergen
from sleepy import buzzergenimport timebuzzer = buzzergen(3) # Planning to wake up each 3 secondsprint time.time()buzzer.next()print time.time()time.sleep(2)buzzer.next()print time.time()time.sleep(5) # Sleeping a bit longer than usuallybuzzer.next()print time.time()buzzer.next()print time.time()
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completedfrom time import sleep, time
def party_later(kind='', n=''):sleep(3)return kind + n + ' party time!: ' + __name__
def main():with ProcessPoolExecutor() as proc_executor:with ThreadPoolExecutor() as thread_executor:start_time = time()proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')for f in as_completed([proc_future1, proc_future2, thread_future1, thread_future2,]):print(f.result())end_time = time()print('total time to execute four 3-sec functions:', end_time - start_time)
if __name__ == '__main__':main()
此脚本的示例输出:
thread1 party time!: __main__thread2 party time!: __main__proc1 party time!: __mp_main__proc2 party time!: __mp_main__total time to execute four 3-sec functions: 3.4519670009613037
import pygame# If you are going to use the time module# don't do "from pygame import *"pygame.init()print('Hello')pygame.time.wait(5000) # Millisecondsprint('Bye')
import tkinter as tk # Tkinter for Python 2root = tk.Tk()print('Hello')def ohhi():print('Oh, hi!')root.after(5000, ohhi) # Milliseconds and then a functionprint('Bye')
import time
def delay(period='5'):# If the user enters nothing, it'll wait 5 secondstry:# If the user not enters a int, I'll just return ''time.sleep(period)except:return ''
import asynciofrom datetime import datetime
@asyncio.coroutinedef countdown(iteration_name, countdown_sec):"""Just count for some countdown_sec seconds and do nothing else"""while countdown_sec > 0:print(f'{iteration_name} iterates: {countdown_sec} seconds')yield from asyncio.sleep(1)countdown_sec -= 1
loop = asyncio.get_event_loop()tasks = [asyncio.ensure_future(countdown('First Count', 2)),asyncio.ensure_future(countdown('Second Count', 3))]
start_time = datetime.utcnow()
# Run both methods. How much time will both run...?loop.run_until_complete(asyncio.wait(tasks))
loop.close()
print(f'total running time: {datetime.utcnow() - start_time}')
from threading import Eventfrom time import sleep
delay_in_sec = 2
# Use time.sleep like thissleep(delay_in_sec) # Returns Noneprint(f'slept for {delay_in_sec} seconds')
# Or use Event().wait like thisEvent().wait(delay_in_sec) # Returns Falseprint(f'waited for {delay_in_sec} seconds')
from threading import Timer
delay_in_sec = 2
def hello(delay_in_sec):print(f'function called after {delay_in_sec} seconds')
t = Timer(delay_in_sec, hello, [delay_in_sec]) # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parametert.start() # Returns Noneprint("Started")