Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改调度时间-Python_Python_Python 3.x_Scheduled Tasks_Scheduler - Fatal编程技术网

更改调度时间-Python

更改调度时间-Python,python,python-3.x,scheduled-tasks,scheduler,Python,Python 3.x,Scheduled Tasks,Scheduler,我正在使用调度模块自动运行一个函数 我正在考虑动态更改调度时间,但解决方案并不成功 代码- 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

我正在使用调度模块自动运行一个函数

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

代码-

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秒运行一次。如果随机整数-
索引
值变为2,则
时间
变量被指定为
1
(1分钟)。我选中了,在随机整数
索引
变为2后,
time
变量变为1。问题-将
time
变量更改为1后,调度仍会每隔6秒而不是1分钟运行函数
a()

如何动态更改调度时间

多谢各位

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

这是因为
schedule.every(time).minutes.do(a)#指定自动运行api的分钟数
在开始时将
时间
设置为6秒,即使您更改该变量的值,该时间也不会更改,因为该行在执行时时间的值为6秒时只执行了一次

如何动态更改调度时间

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

在您的情况下,您可以:

计划。每(5)到(10)秒。执行(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