簡體   English   中英

Python 線程定時器未填充 output 文件

[英]Python threading Timer not filling output file

我正在使用模塊線程 class 定時器。 我想設置一個每天都會重復的過程,每次啟動(天)都會生成一個 output 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()

所以所有的腳本都可以正常運行,如果我注釋了所有 Timer 部分,我會得到 json 文件。 但是當我開始每天運行該進程時,它會生成空的 json 文件(未填充)。

怎么了? 如何在 function geojson_gen() 完成后(而不是在整個 Timer 過程之后)填充 json?

非常感謝!

使用給定的代碼,我不知道為什么會生成空文件,但是並行啟動許多 Timer 對您的目標來說並不是一個好的解決方案。 因為你想要的不是一個並行的過程,而是一個重復的、連續的過程。

一種更有效的方法是創建基於時間的循環。 這個例子展示了基本思想:

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()

這意味着您必須讓腳本運行。 更簡潔的解決方案是僅使用創建 json 的腳本,然后在您的操作系統中安排每天運行該腳本。 有關 Windows 示例,請參閱此答案

我對使用threading.Timer()的腳本有類似的問題,該腳本只是在執行print() 這可以從終端工作,但是當將 output 傳輸到文件時,該文件只會很少更新。 這意味着我不能做tail -f 通過添加sys.stdout.flush()解決了這個問題。 不確定這是否有助於 OP,但它可能是正確方向的提示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM