Python 线程计时器未填充输出文件
Python threading Timer not filling output file
我正在使用线程模块 class 定时器。我想设置一个每天重复的过程,每次启动时(天)生成一个输出 json 文件。
问题是它生成的文件在整个过程完成之前不会被填充(所以如果它必须 运行 一整年,我将等待一整年)。
这里是代码。
from processing import *
import sys
from datetime import datetime, timedelta
from threading import Timer
if __name__ == "__main__":
'''
'''
#Function that generates a json file, that (works), but only is filled if Timer is NOT runing
geojson_gen(sys.argv[1],
sys.argv[2],
sys.argv[3],
out_filename = 'test_country'
)
for rep in range(10000):
#Get the number of seconds for the next time Timer will launch the func. geojson_gen(). Here some code to get the number of seconds in which it shall be launched the timer
next_date = (launch_date - start_date).seconds
t = Timer(next_date , geojson_gen(sys.argv[1],
sys.argv[2],
sys.argv[3],
out_filename = 'test_country'
)
)
t.start()
所以所有脚本 运行 都是正确的,如果我注释所有计时器部分,我会得到 json 文件。但是当我每天开始 运行 的过程时,它会生成空的 json 文件(未填充)。
怎么了?如何在函数 geojson_gen() 完成后(而不是在整个 Timer 过程之后)填充 json?
非常感谢!
根据给出的代码,我不知道为什么会生成空文件,但是并行启动大量计时器并不是实现您的目标的好解决方案。因为你想要的不是一个并行的过程,而是一个重复的、顺序的过程。
一种更有效的方法是创建一个基于时间的循环。这个例子展示了基本思想:
import time
#set the wait time (a day in seconds)
waitTime = 60*60*24
# set initial value
startTime = time.time()
# runs forever
while True:
# check how much time has passed
timeDiff = time.time() - startTime
# if a day has passed, generate a json and update starttime
if timeDiff > waitTime:
geojson_gen()
startTime = time.time()
这意味着您必须离开脚本 运行ning。一个更简洁的解决方案是只使用创建 json 的脚本,然后每天安排 OS 到 运行 该脚本。有关 Windows 示例,请参阅 。
我正在使用线程模块 class 定时器。我想设置一个每天重复的过程,每次启动时(天)生成一个输出 json 文件。
问题是它生成的文件在整个过程完成之前不会被填充(所以如果它必须 运行 一整年,我将等待一整年)。
这里是代码。
from processing import *
import sys
from datetime import datetime, timedelta
from threading import Timer
if __name__ == "__main__":
'''
'''
#Function that generates a json file, that (works), but only is filled if Timer is NOT runing
geojson_gen(sys.argv[1],
sys.argv[2],
sys.argv[3],
out_filename = 'test_country'
)
for rep in range(10000):
#Get the number of seconds for the next time Timer will launch the func. geojson_gen(). Here some code to get the number of seconds in which it shall be launched the timer
next_date = (launch_date - start_date).seconds
t = Timer(next_date , geojson_gen(sys.argv[1],
sys.argv[2],
sys.argv[3],
out_filename = 'test_country'
)
)
t.start()
所以所有脚本 运行 都是正确的,如果我注释所有计时器部分,我会得到 json 文件。但是当我每天开始 运行 的过程时,它会生成空的 json 文件(未填充)。
怎么了?如何在函数 geojson_gen() 完成后(而不是在整个 Timer 过程之后)填充 json?
非常感谢!
根据给出的代码,我不知道为什么会生成空文件,但是并行启动大量计时器并不是实现您的目标的好解决方案。因为你想要的不是一个并行的过程,而是一个重复的、顺序的过程。
一种更有效的方法是创建一个基于时间的循环。这个例子展示了基本思想:
import time
#set the wait time (a day in seconds)
waitTime = 60*60*24
# set initial value
startTime = time.time()
# runs forever
while True:
# check how much time has passed
timeDiff = time.time() - startTime
# if a day has passed, generate a json and update starttime
if timeDiff > waitTime:
geojson_gen()
startTime = time.time()
这意味着您必须离开脚本 运行ning。一个更简洁的解决方案是只使用创建 json 的脚本,然后每天安排 OS 到 运行 该脚本。有关 Windows 示例,请参阅