微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更改计划时间-Python

如何解决更改计划时间-Python

我正在使用计划模块自动运行功能...

我正在考虑动态更改计划时间,但解决方案并不成功

代码-

import schedule
import pandas
from time import gmtime,strftime,sleep
import time
import random

time = 0.1
def a():
    global time
    print(strftime("%Y-%m-%d %H:%M:%s",gmtime()))
    index = random.randint(1,9)
    print(index,time)
    if(index==2):
        time = 1

print(strftime("%Y-%m-%d %H:%M:%s",gmtime()))
schedule.every(time).minutes.do(a) #specify the minutes to automatically run the api

while True:
    schedule.run_pending()

在此程序中,我安排了该程序每6秒运行一次。并且,如果随机整数-index的值变为2,则将time变量分配为1(1分钟)。我检查过,time变量在随机整数index变为2后更改为1。问题-将time变量更改为1后,调度仍运行函数{{1 }}每6秒而不是1分钟。

如何动态更改计划时间?

谢谢

解决方法

将时间变量更改为1后,调度程序仍每6秒而不是1分钟运行一次a()函数。

这是因为schedule.every(time).minutes.do(a) # specify the minutes to automatically run the api在开始时将time设置为 6秒,即使您更改了该变量的值也不会更改,因为该行仅执行了一次在执行该操作时,时间的值为 6秒

如何动态更改计划时间?

阅读DOCUMENTATION后,我没有发现关于时间的手动更改(我认为)(当某些条件满足时)但它内置了Random Interval函数,该函数本身指定了随机时间within the range

您可以这样做:

schedule.every(5).to(10).seconds.do(a)

问题在于,当某些条件满足时,您不能更改时间

也许可能有一些方法可以解决该问题,但无法解决。这些信息可能有助于进一步调查以解决您的问题。

,

我通常使用自定义调度程序,因为它们可以提供更大的控制力,并且占用的内存更少。变量“时间”需要在进程之间共享。这是Manager()。Namespace()抢救的地方。它谈到“之间”的过程。

import time
import random
from multiprocessing import Process,Manager

ns = Manager().Namespace()
ns.time = 0.1
processes = []

def a():
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
    index = random.randint(1,4)
    if(index==2):
        ns.time = 1
    print(index,ns.time)

while True:
    try:
        s = time.time() + ns.time*60
        for x in processes:
            if not x.is_alive():
                x.join()
                processes.remove(x)
        print('Sleeping :',round(s - time.time()))
        time.sleep(round(s - time.time()))
        p = Process(target = a)
        p.start()
        processes.append(p)
    except:
        print('Killing all to prevent orphaning ...')
        [p.terminate() for p in processes]
        [processes.remove(p) for p in processes]
        break

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。