[英]Start a new timer based thread after previous one finished in python
我想在每次 60 秒之后的某个时间运行这个文件移动器功能。 但是如果之前的文件移动函数没有完成,那么这个函数的新线程在 60s 之后就不会运行。它只会在没有线程已经运行并且时间为 60s 时运行。 我怎样才能实现这个功能? 预先感谢您的帮助。
我对线程的了解有限。
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 秒后休眠,以便其他线程或线程可以启动
虽然我会建议不要这样做,因为如果您对它有点陌生,它可能会在可维护性方面很快失控。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.