本站使用了 Pjax 等基于 JavaScript 的开发技术,但您的浏览器已禁用 JavaScript,请开启 JavaScript 以保证网站正常显示!

Python学习记录_每个一段时间执行任务

来源:小树苗blog , 访问原文
因为需求比较简单, 所以最后用了while True: + time.sleep()解决的.

小树苗代码

#Function: 每隔一段时间做一个事情   
from datetime import date, time, datetime, timedelta

#要做的事情   
def work():
    print ('hello world.')
def runTask(func, day=0, hour=0, min=0, second=0):
# Init time
    now = datetime.now()
    strnow = now.strftime('%Y-%m-%d %H:%M:%S')
    print ('now:',strnow)
    # First next run time
    period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
    next_time = now + period
    strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
    print ('next run:',strnext_time)
    while True:
        # Get system current time
        iter_now = datetime.now()
        iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
        if str(iter_now_time) == str(strnext_time):
            # Get every start work time
            print ('start work: %s' % iter_now_time)
            # Call task func
            work()
            print ('task done.')
            # Get next iteration time
            iter_time = iter_now + period
            strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
            print ('next_iter: %s' % strnext_time)
            # Continue next iteration
            continue
# runTask(work, min=0.5)
runTask(work(), day=0, hour=0, min=0,second=10)

我的代码

while True:
    time.sleep(1000)
    run_work()

帮助小微企业构建在线化、智能化的经营管理体系,让经营管理更轻松!

推广

 继续浏览关于 datetime 的文章

 本文最后更新于:2020/01/11 14:55:32,可能因经年累月而与现状有所差异,有任何疑问可以随时与258771198@qq.com沟通,邮箱永久有效

 引用转载请注明:魔码科技 > Python > Python学习记录_每个一段时间执行任务

发现共鸣

如是说:我觉得,我这辈子最灿烂的笑容,大概都奉献给我电脑屏幕了。