在前一个线程在python中完成后启动新的基于计时器的线程
我想在特定的时间运行这个filemover函数,比如每次60秒后。但是,如果以前的文件移动器函数尚未完成,则此函数的新线程在60秒后将不会运行。它将仅在没有线程已在运行且时间为60秒时运行。如何实现此功能?事先谢谢你的帮助 我对线程的知识有限在前一个线程在python中完成后启动新的基于计时器的线程,python,multithreading,Python,Multithreading,我想在特定的时间运行这个filemover函数,比如每次60秒后。但是,如果以前的文件移动器函数尚未完成,则此函数的新线程在60秒后将不会运行。它将仅在没有线程已在运行且时间为60秒时运行。如何实现此功能?事先谢谢你的帮助 我对线程的知识有限 def filemover(): threading.Timer(60.0, filemover).start() oldp="D:/LCT Work/python code/projectexcelupload/notprocessed"
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()
嗯,我建议的原则有点不同。每次执行一个线程时,都必须创建一个锁,以便其他线程知道其他线程在同一时间执行。我认为最简单的方法是创建和删除锁文件。我头顶上的例子是这样的:
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()
线程的工作方式是,除非另一个线程当前不工作,否则另一个线程不会开始,因此,除非另一个线程完成,否则另一个线程在60秒后不会开始是有意义的。你能做什么 这个程序有两个time.sleep()函数,例如,如果您有一个代码
def stuff():
print('hello threads')
time.sleep(1)
print('done')
stuff()
stuff()
但如果您使用的是线程,它看起来更像
如果你仔细观察,你会发现下一个函数就在另一个开始睡眠时启动。线程不并发运行,可以运行一个线程,但不能运行两个线程,这将是多处理。
在代码中,您使用的是threading.Timer()
函数。问题是两个线程不能同时运行。如果你想要这个功能,你必须重构你的代码。您可以决定在要使用线程的函数中设置时间限制,以使用时间模块,使其在60秒后休眠,以便其他线程可以启动
尽管我建议您不要这样做,因为如果您对可维护性有点陌生,它可能会很快失控。这种方法不是让cpu总是在高cpu使用率下忙碌吗?原因
while(os.path.exists(“thread.lck”):
循环将为正在等待使用lck文件的线程的其他线程连续运行。原因filemover不是我正在使用的唯一函数。还有其他用于在数据库中上载文件的功能。我还没有给他们。因为我想让它变得简单。这就是为什么你有这样一个答案,在你的问题中缺乏数据。是的,线程经常忙于检查状态。如果你正在寻找更优化的解决方案,你应该考虑使用好的旧中断,或者甚至在第二级线程。但是另一个线程是在我之前测试的线程的中间开始的。代码是“代码> DEF HeloLoE():t=线程。定时器(1,hello)t开始())打印(“hello线程”)为i在范围(0, 10000)中。:print(i)print('done')def mainfn():hello()mainfn()问题应该重新措辞,并添加更多信息。