更改调度时间 - Python [英] Change the Scheduling Time - Python
问题描述
我正在使用 schedule 模块来自动运行一个函数...
I am using schedule module to automatically run a function...
我正在考虑动态更改调度时间,但解决方法不成功
I am thinking of changing the scheduling time dynamically, but the solution is not success
代码 -
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 分钟).我查了一下,随机整数 index
变为 2 后,time
变量变为 1.问题 - 将 time
变量变为 1 后,调度仍然每 6 秒而不是 1 分钟运行一次函数 a()
.
In this program, I scheduled the program to run every 6 seconds. And if the random integer - index
value becomes 2, then the time
variable is assigned as 1
(1 minute). I checked, the time
variable is changed to 1 after the random integer index
becomes 2. The issue - After changing the time
variable to 1, the scheduling still runs the function a()
every 6 seconds not 1 minute.
如何动态改变调度时间?
How to change the scheduling time dynamically?
谢谢
推荐答案
我通常使用自定义调度程序,因为它们允许更好的控制并且占用更少的内存.变量时间"需要在进程之间共享.这就是 Manager().Namespace() 来拯救的地方.它在进程之间进行对话.
I usually use custom schedulers, as they allow greater control and are also less memory intensive. The variable "time" needs to be shared between processes. This is where Manager().Namespace() comes to rescue. It talks 'between' processes.
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
这篇关于更改调度时间 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!