在Python中如何每2秒调用一次函数?

在Python中如何每2秒调用一次函数?,python,python-3.x,Python,Python 3.x,我试图弄清楚如何在Python中每隔2秒调用一次函数? 我应该使用定时器还是线程? 任何人都可以提供链接/示例吗?模块可以这样做: import sched, time schedTimer = sched.scheduler(time.time, time.sleep) def increaseX(x): x += 1 print('X increased to ' + str(x)) schedTimer.enter(2, 1, increaseX, (x,)) sc

我试图弄清楚如何在Python中每隔2秒调用一次函数? 我应该使用定时器还是线程? 任何人都可以提供链接/示例吗?

模块可以这样做:

import sched, time
schedTimer = sched.scheduler(time.time, time.sleep)
def increaseX(x):
    x += 1
    print('X increased to ' + str(x))
    schedTimer.enter(2, 1, increaseX, (x,))
schedTimer.enter(2, 1, increaseX, (3,))
schedTimer.run()

请提供有关要求的更多细节。根据您可以容忍的延迟、通话间隔的准确程度以及您是否可以容忍任何未接来电,方法会有所不同。