使用python在前一个线程完成后启动一个新的基于计时器的线程

2024-10-01 22:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在某个特定的时间运行这个filemover函数,比如每次60后。但是如果以前的文件移动器函数还没有完成,那么这个函数在60秒后的新线程将不会运行快跑,快点只有在没有线程运行且时间为60秒时才会运行。如何实现此功能?事先谢谢你的帮助。你知道吗

我对线程的知识有限。你知道吗

def filemover():
    threading.Timer(60.0, filemover).start()
    oldp="D:/LCT Work/python code/projectexcelupload/notprocessed"
    newp="D:/LCT Work/python code/projectexcelupload/processed"
    onlyfiles = [f for f in listdir(oldp) if isfile(join(oldp, f))]
    #print(onlyfiles.index("hello"))
    global globalfilenamearra
    global globalpos
    for file in onlyfiles:
        if (file in globalfilenamearra):
            txt=1
        else:
            globalfilenamearra.append(file)

filemover()

Tags: 函数inforif时间code线程file
2条回答

线程的工作方式是另一个线程不开始,除非另一个线程当前不工作,因此另一个线程在60秒后不会开始,除非另一个线程完成。你能做什么 a function without threads 这个程序有两个时间。睡眠()函数,例如,如果有代码

def stuff():
    print('hello threads')
    time.sleep(1)
    print('done')

stuff()
stuff()

但是如果您使用线程,它看起来更像 inner workings of threads 如果你仔细观察,你会发现下一个函数就在另一个开始睡眠时开始。线程不会同时运行,其中一个线程可以运行,但两个线程不能同时运行,这将是多进程的。 在代码中使用的是threading.Timer()函数。问题是两个线程不能同时运行。如果你想要这个功能,你必须重构你的代码。您可以决定在使用时间模块时要使用线程的函数中设置时间限制,使其在60秒后休眠,以便其他线程可以启动

尽管我建议不要这样做,因为如果您对它有些陌生的话,当涉及到可维护性时,它可能会很快失控。你知道吗

好吧,我建议的原则有点不同。每次执行一个线程时,都必须创建一个锁,以便其他线程知道其他线程在同一时间执行。我想说最简单的方法是创建和删除锁文件。我脑海中的例子是这样的:

import os
import shutil
import threading

def moveFile(source, destination):
    print("waiting for other to finish\n")
    error_flag = 0
    while(os.path.exists("thread.lck")):
        error_flag = 0
    print("creating the new lock\n")
    f = open("thread.lck", "w")
    f.write("You can even do the identification of threads if you want")
    f.close()
    print("starting the work\n")
    if(os.path.exists(source) and os.path.exist(destination)==False):
        shutil.move(source, destination)
    else:
        error_flag = 1
    print("remove the lock")
    os.remove("thread.lck")
    return error_flag


for i in range(0, 5):
    threading.Timer(1.0*i, moveFile, args=("some.txt", "some1.txt")).start()

相关问题 更多 >

    热门问题