1. 使用`time.sleep()`函数:
```python
import time
while True:
执行任务
time.sleep(10) 等待10秒后继续执行下一次任务
2. 使用`threading.Timer`类:
```python
from threading import Timer
def task():
print("执行定时任务")
Timer(10, task).start() 每隔10秒执行一次任务
3. 使用`sched`模块:
```python
import sched
import time
s = sched.scheduler(time.time, time.sleep)
def perform_command(cmd, inc):
os.system(cmd)
print('task')
def timming_exe(cmd, inc=60):
s.enter(inc, 0, perform_command, (cmd, inc))
s.run()
print('show time after 2 seconds:')
timming_exe('echo %time%') 每隔2秒执行一次任务
4. 使用`APScheduler`库:
```python
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print("Job is running!")
scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', seconds=5)
scheduler.start() 每隔5秒执行一次任务
5. 使用第三方库`schedule`:
```python
import schedule
import time
def job():
print("Job is running!")
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1) 每隔5秒执行一次任务
选择适合你需求的方法来实现定时任务。如果你需要更复杂的调度功能,比如固定时间执行、固定日期执行等,`APScheduler`提供了更丰富的选项。如果你只需要简单的定时任务,`time.sleep()`或`sched`模块就足够了