[英]Run two python functions simultaneously with sleep
I have two functions but I can't get them to run all the time with the foo()
function that sleeps for some time.我有两个函数,但我无法让它们一直运行,而
foo()
函数会休眠一段时间。
import time
filename = "test.dat"
def foo():
print "It deletes dat file and creates a new one"
time.sleep(xxx)
def bar():
print "Writes to dat file"
while True:
foo()
bar()
I'm not sure that I correctly understood the problem, but try this one and let me know if that is what you want我不确定我是否正确理解了这个问题,但试试这个,让我知道这是否是你想要的
import time
from multiprocessing import Process
def foo(x):
while True:
print ("It deletes dat file and creates new one")
time.sleep(x)
def bar():
while True:
print ("Wtires to dat file")
process1 = Process(target=foo, args=(0.05,))
process2 = Process(target=bar)
process1.start()
process2.start()
with this code foo()
will run with x = 0.05
seconds break and bar()
will run all the time... but note that "all the time" means veeeeery often and with no breaks:)使用此代码
foo()
将在x = 0.05
秒中断时运行,而bar()
将一直运行...
问题是: filename
被定义为一个global variable
,一旦foo()
删除该文件并创建一个新filename
, filename
就变成了一个local variable
,所以bar()
函数找不到dat
文件,这就是它这样做的原因根本不跑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.