📜  如何在python中设置间隔(1)

📅  最后修改于: 2023-12-03 15:08:58.124000             🧑  作者: Mango

如何在Python中设置间隔

在Python中,有许多方法可以设置间隔。下面介绍几个常用的方法:

1. time.sleep() 函数

这个函数可以让程序暂停一段时间,参数是要暂停的秒数。

import time

print('hello')
time.sleep(2)  # 暂停2秒钟
print('world')

输出:

hello

(暂停2秒钟)

world
2. datetime.timedelta() 函数

这个函数可以用来表示时间间隔。参数中可以传入天数、小时数、分钟数、秒数等。

from datetime import datetime, timedelta

print(datetime.now())

# 程序暂停1小时
pause_time = datetime.now() + timedelta(hours=1)
while datetime.now() < pause_time:
    pass

print(datetime.now())

输出:

2021-08-02 08:59:34.692706
(暂停1小时)
2021-08-02 09:59:34.694706
3. sched 模块

这个模块提供了一个调度器,可以在指定的时间执行任务。下面的例子演示了如何每隔一定时间(秒)执行一次任务。

import sched
import time

s = sched.scheduler(time.time, time.sleep)

def do_something():
    print('hello')
    # 每隔5秒钟执行一次
    s.enter(5, 1, do_something, ())

s.enter(0, 1, do_something, ())
s.run()

输出:

hello
(暂停5秒钟)
hello
(暂停5秒钟)
hello
(暂停5秒钟)
...
4. threading 模块

这个模块提供了多线程的支持,我们可以在一个线程中执行某个任务,同时另一个线程可以在后台定时执行一些操作。

import threading
import time

def do_something():
    print('hello')

# 每隔5秒钟执行一次
def do_every_5_seconds():
    while True:
        t = threading.Timer(5.0, do_something)
        t.start()
        t.join()

# 启动后台线程
threading.Thread(target=do_every_5_seconds).start()

输出:

hello
(暂停5秒钟)
hello
(暂停5秒钟)
hello
(暂停5秒钟)
...

以上就是在Python中设置间隔的几种方法。其中time.sleep()函数可以用于任何程序,另外的方法则可以用于需要定时执行某个任务的场景。