背景
最近遇到一个需求,每隔一段时间需要获取接口中的数据。这就需要用到定时任务,通过对指定函数设置定时任务,可以每个一段时间重新调用该函数,达到我们想要的结果。当然,实现定时任务的方法有很多种比如使用while+sleep、使用Timer函数、使用schedule任务调度模块、以及使用APScheduler定时任务框架等。这里我采用Timer函数完成定时操作。
需求
每隔5秒获取当前的时间。
代码
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :python-learning
@File :test_auto_start.py
@Description:测试python一段时间内自动启动---自动启动的是python程序中的某个函数
@Author :heisenberg
@Date :2021/10/11 15:35
'''
import time
from threading import Timer
class test_auto_start_function():
# 获取当前时间
def get_time(self,seconds):
'''
:param seconds: 每次获取时间的间隔时间
:return:
'''
now_time = time.time()
print('当前时间为:', now_time)
global t
t = Timer(seconds, test_auto_start_function().get_time,(seconds,))
t.start()
# 其他函数,判断程序执行时该函数是否被执行
def other(self):
print('hahaha')
if __name__ == '__main__':
tasf = test_auto_start_function()
tasf.get_time(5)