Python定时任务

def work():
    print "hello work"
def runTaskOnly(func, day=0, hour=0, min=0, second=0):
    now = datetime.now()
    strnow = now.strftime('%Y-%m-%d %H:%M:%S')
    print "现在时间:",strnow
    period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
    print "间隔时间:",period
    next_time = now + period
    strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
    print "首次运行时间:",strnext_time
    while True:
        iter_now = datetime.now()
        iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
        if str(iter_now_time) == str(strnext_time):
            print "任务开始: %s" % iter_now_time
            func()
            print "执行完成."
            break

def runTaskMore(func, day=0, hour=0, min=0, second=0):
    # Init time
    now = datetime.now()
    strnow = now.strftime('%Y-%m-%d %H:%M:%S')
    print "现在时间:",strnow
    # First next run time
    period = timedelta(days=day, hours=hour, minutes=min, seconds=second)
    print "间隔时间:",period
    next_time = now + period
    strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S')
    print "首次运行时间:",strnext_time
    while True:
        iter_now = datetime.now()
        iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S')
        if str(iter_now_time) == str(strnext_time):
            print "任务开始: %s" % iter_now_time
            func()
            print "执行完成"
            iter_time = iter_now + period
            strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
            print "再次运行时间: %s" % strnext_time
            continue

runTaskOnly(work, day=1, hour=1, min=2)#间隔1天1小时2分钟后执行
runTaskMore(work, day=1, hour=1, min=2)#每隔1天1小时2分钟执行一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值